1 /* Built-in functions */
4 #include "Python-ast.h"
11 #include <float.h> /* for DBL_MANT_DIG and friends */
14 #include "unixstuff.h"
17 /* The default encoding used by the platform file system APIs
18 Can remain NULL for all platforms that don't have such a concept
20 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
21 const char *Py_FileSystemDefaultEncoding
= "mbcs";
22 #elif defined(__APPLE__)
23 const char *Py_FileSystemDefaultEncoding
= "utf-8";
25 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
29 static PyObject
*filterstring(PyObject
*, PyObject
*);
30 #ifdef Py_USING_UNICODE
31 static PyObject
*filterunicode(PyObject
*, PyObject
*);
33 static PyObject
*filtertuple (PyObject
*, PyObject
*);
36 builtin___import__(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
38 static char *kwlist
[] = {"name", "globals", "locals", "fromlist",
41 PyObject
*globals
= NULL
;
42 PyObject
*locals
= NULL
;
43 PyObject
*fromlist
= NULL
;
46 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "s|OOOi:__import__",
47 kwlist
, &name
, &globals
, &locals
, &fromlist
, &level
))
49 return PyImport_ImportModuleLevel(name
, globals
, locals
,
53 PyDoc_STRVAR(import_doc
,
54 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
56 Import a module. The globals are only used to determine the context;\n\
57 they are not modified. The locals are currently unused. The fromlist\n\
58 should be a list of names to emulate ``from name import ...'', or an\n\
59 empty list to emulate ``import name''.\n\
60 When importing a module from a package, note that __import__('A.B', ...)\n\
61 returns package A when fromlist is empty, but its submodule B when\n\
62 fromlist is not empty. Level is used to determine whether to perform \n\
63 absolute or relative imports. -1 is the original strategy of attempting\n\
64 both absolute and relative imports, 0 is absolute, a positive number\n\
65 is the number of parent directories to search relative to the current module.");
69 builtin_abs(PyObject
*self
, PyObject
*v
)
71 return PyNumber_Absolute(v
);
75 "abs(number) -> number\n\
77 Return the absolute value of the argument.");
80 builtin_all(PyObject
*self
, PyObject
*v
)
83 PyObject
*(*iternext
)(PyObject
*);
86 it
= PyObject_GetIter(v
);
89 iternext
= *Py_TYPE(it
)->tp_iternext
;
95 cmp
= PyObject_IsTrue(item
);
107 if (PyErr_Occurred()) {
108 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
116 PyDoc_STRVAR(all_doc
,
117 "all(iterable) -> bool\n\
119 Return True if bool(x) is True for all values x in the iterable.");
122 builtin_any(PyObject
*self
, PyObject
*v
)
125 PyObject
*(*iternext
)(PyObject
*);
128 it
= PyObject_GetIter(v
);
131 iternext
= *Py_TYPE(it
)->tp_iternext
;
137 cmp
= PyObject_IsTrue(item
);
149 if (PyErr_Occurred()) {
150 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
158 PyDoc_STRVAR(any_doc
,
159 "any(iterable) -> bool\n\
161 Return True if bool(x) is True for any x in the iterable.");
164 builtin_apply(PyObject
*self
, PyObject
*args
)
166 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
167 PyObject
*t
= NULL
, *retval
= NULL
;
169 if (PyErr_WarnPy3k("apply() not supported in 3.x; "
170 "use func(*args, **kwargs)", 1) < 0)
173 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
176 if (!PyTuple_Check(alist
)) {
177 if (!PySequence_Check(alist
)) {
178 PyErr_Format(PyExc_TypeError
,
179 "apply() arg 2 expected sequence, found %s",
180 alist
->ob_type
->tp_name
);
183 t
= PySequence_Tuple(alist
);
189 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
190 PyErr_Format(PyExc_TypeError
,
191 "apply() arg 3 expected dictionary, found %s",
192 kwdict
->ob_type
->tp_name
);
195 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
201 PyDoc_STRVAR(apply_doc
,
202 "apply(object[, args[, kwargs]]) -> value\n\
204 Call a callable object with positional arguments taken from the tuple args,\n\
205 and keyword arguments taken from the optional dictionary kwargs.\n\
206 Note that classes are callable, as are instances with a __call__() method.\n\
208 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
209 function(*args, **keywords).");
213 builtin_bin(PyObject
*self
, PyObject
*v
)
215 return PyNumber_ToBase(v
, 2);
218 PyDoc_STRVAR(bin_doc
,
219 "bin(number) -> string\n\
221 Return the binary representation of an integer or long integer.");
225 builtin_callable(PyObject
*self
, PyObject
*v
)
227 if (PyErr_WarnPy3k("callable() not supported in 3.x; "
228 "use isinstance(x, collections.Callable)", 1) < 0)
230 return PyBool_FromLong((long)PyCallable_Check(v
));
233 PyDoc_STRVAR(callable_doc
,
234 "callable(object) -> bool\n\
236 Return whether the object is callable (i.e., some kind of function).\n\
237 Note that classes are callable, as are instances with a __call__() method.");
241 builtin_filter(PyObject
*self
, PyObject
*args
)
243 PyObject
*func
, *seq
, *result
, *it
, *arg
;
244 Py_ssize_t len
; /* guess for result list size */
245 register Py_ssize_t j
;
247 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
250 /* Strings and tuples return a result of the same type. */
251 if (PyString_Check(seq
))
252 return filterstring(func
, seq
);
253 #ifdef Py_USING_UNICODE
254 if (PyUnicode_Check(seq
))
255 return filterunicode(func
, seq
);
257 if (PyTuple_Check(seq
))
258 return filtertuple(func
, seq
);
260 /* Pre-allocate argument list tuple. */
261 arg
= PyTuple_New(1);
266 it
= PyObject_GetIter(seq
);
270 /* Guess a result list size. */
271 len
= _PyObject_LengthHint(seq
, 8);
275 /* Get a result list. */
276 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
277 /* Eww - can modify the list in-place. */
282 result
= PyList_New(len
);
287 /* Build the result list. */
293 item
= PyIter_Next(it
);
295 if (PyErr_Occurred())
300 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
301 ok
= PyObject_IsTrue(item
);
305 PyTuple_SET_ITEM(arg
, 0, item
);
306 good
= PyObject_Call(func
, arg
, NULL
);
307 PyTuple_SET_ITEM(arg
, 0, NULL
);
312 ok
= PyObject_IsTrue(good
);
317 PyList_SET_ITEM(result
, j
, item
);
319 int status
= PyList_Append(result
, item
);
331 /* Cut back result list if len is too big. */
332 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
348 PyDoc_STRVAR(filter_doc
,
349 "filter(function or None, sequence) -> list, tuple, or string\n"
351 "Return those items of sequence for which function(item) is true. If\n"
352 "function is None, return the items that are true. If sequence is a tuple\n"
353 "or string, return the same type, else return a list.");
356 builtin_format(PyObject
*self
, PyObject
*args
)
359 PyObject
*format_spec
= NULL
;
361 if (!PyArg_ParseTuple(args
, "O|O:format", &value
, &format_spec
))
364 return PyObject_Format(value
, format_spec
);
367 PyDoc_STRVAR(format_doc
,
368 "format(value[, format_spec]) -> string\n\
370 Returns value.__format__(format_spec)\n\
371 format_spec defaults to \"\"");
374 builtin_chr(PyObject
*self
, PyObject
*args
)
379 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
381 if (x
< 0 || x
>= 256) {
382 PyErr_SetString(PyExc_ValueError
,
383 "chr() arg not in range(256)");
387 return PyString_FromStringAndSize(s
, 1);
390 PyDoc_STRVAR(chr_doc
,
391 "chr(i) -> character\n\
393 Return a string of one character with ordinal i; 0 <= i < 256.");
396 #ifdef Py_USING_UNICODE
398 builtin_unichr(PyObject
*self
, PyObject
*args
)
402 if (!PyArg_ParseTuple(args
, "i:unichr", &x
))
405 return PyUnicode_FromOrdinal(x
);
408 PyDoc_STRVAR(unichr_doc
,
409 "unichr(i) -> Unicode character\n\
411 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
416 builtin_cmp(PyObject
*self
, PyObject
*args
)
421 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
423 if (PyObject_Cmp(a
, b
, &c
) < 0)
425 return PyInt_FromLong((long)c
);
428 PyDoc_STRVAR(cmp_doc
,
429 "cmp(x, y) -> integer\n\
431 Return negative if x<y, zero if x==y, positive if x>y.");
435 builtin_coerce(PyObject
*self
, PyObject
*args
)
440 if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
443 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
445 if (PyNumber_Coerce(&v
, &w
) < 0)
447 res
= PyTuple_Pack(2, v
, w
);
453 PyDoc_STRVAR(coerce_doc
,
454 "coerce(x, y) -> (x1, y1)\n\
456 Return a tuple consisting of the two numeric arguments converted to\n\
457 a common type, using the same rules as used by arithmetic operations.\n\
458 If coercion is not possible, raise TypeError.");
461 builtin_compile(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
467 int dont_inherit
= 0;
468 int supplied_flags
= 0;
471 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
473 static char *kwlist
[] = {"source", "filename", "mode", "flags",
474 "dont_inherit", NULL
};
475 int start
[] = {Py_file_input
, Py_eval_input
, Py_single_input
};
477 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oss|ii:compile",
478 kwlist
, &cmd
, &filename
, &startstr
,
479 &supplied_flags
, &dont_inherit
))
482 cf
.cf_flags
= supplied_flags
;
485 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
487 PyErr_SetString(PyExc_ValueError
,
488 "compile(): unrecognised flags");
491 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
494 PyEval_MergeCompilerFlags(&cf
);
497 if (strcmp(startstr
, "exec") == 0)
499 else if (strcmp(startstr
, "eval") == 0)
501 else if (strcmp(startstr
, "single") == 0)
504 PyErr_SetString(PyExc_ValueError
,
505 "compile() arg 3 must be 'exec', 'eval' or 'single'");
509 is_ast
= PyAST_Check(cmd
);
513 if (supplied_flags
& PyCF_ONLY_AST
) {
521 arena
= PyArena_New();
522 mod
= PyAST_obj2mod(cmd
, arena
, mode
);
527 result
= (PyObject
*)PyAST_Compile(mod
, filename
,
534 #ifdef Py_USING_UNICODE
535 if (PyUnicode_Check(cmd
)) {
536 tmp
= PyUnicode_AsUTF8String(cmd
);
540 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
544 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
546 if ((size_t)length
!= strlen(str
)) {
547 PyErr_SetString(PyExc_TypeError
,
548 "compile() expected string without null bytes");
551 result
= Py_CompileStringFlags(str
, filename
, start
[mode
], &cf
);
557 PyDoc_STRVAR(compile_doc
,
558 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
560 Compile the source string (a Python module, statement or expression)\n\
561 into a code object that can be executed by the exec statement or eval().\n\
562 The filename will be used for run-time error messages.\n\
563 The mode must be 'exec' to compile a module, 'single' to compile a\n\
564 single (interactive) statement, or 'eval' to compile an expression.\n\
565 The flags argument, if present, controls which future statements influence\n\
566 the compilation of the code.\n\
567 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
568 the effects of any future statements in effect in the code calling\n\
569 compile; if absent or zero these statements do influence the compilation,\n\
570 in addition to any features explicitly specified.");
573 builtin_dir(PyObject
*self
, PyObject
*args
)
575 PyObject
*arg
= NULL
;
577 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
579 return PyObject_Dir(arg
);
582 PyDoc_STRVAR(dir_doc
,
583 "dir([object]) -> list of strings\n"
585 "If called without an argument, return the names in the current scope.\n"
586 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
587 "of the given object, and of attributes reachable from it.\n"
588 "If the object supplies a method named __dir__, it will be used; otherwise\n"
589 "the default dir() logic is used and returns:\n"
590 " for a module object: the module's attributes.\n"
591 " for a class object: its attributes, and recursively the attributes\n"
593 " for any other object: its attributes, its class's attributes, and\n"
594 " recursively the attributes of its class's base classes.");
597 builtin_divmod(PyObject
*self
, PyObject
*args
)
601 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
603 return PyNumber_Divmod(v
, w
);
606 PyDoc_STRVAR(divmod_doc
,
607 "divmod(x, y) -> (div, mod)\n\
609 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
613 builtin_eval(PyObject
*self
, PyObject
*args
)
615 PyObject
*cmd
, *result
, *tmp
= NULL
;
616 PyObject
*globals
= Py_None
, *locals
= Py_None
;
620 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
622 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
623 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
626 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
627 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
628 "globals must be a real dict; try eval(expr, {}, mapping)"
629 : "globals must be a dict");
632 if (globals
== Py_None
) {
633 globals
= PyEval_GetGlobals();
634 if (locals
== Py_None
)
635 locals
= PyEval_GetLocals();
637 else if (locals
== Py_None
)
640 if (globals
== NULL
|| locals
== NULL
) {
641 PyErr_SetString(PyExc_TypeError
,
642 "eval must be given globals and locals "
643 "when called without a frame");
647 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
648 if (PyDict_SetItemString(globals
, "__builtins__",
649 PyEval_GetBuiltins()) != 0)
653 if (PyCode_Check(cmd
)) {
654 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
655 PyErr_SetString(PyExc_TypeError
,
656 "code object passed to eval() may not contain free variables");
659 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
662 if (!PyString_Check(cmd
) &&
663 !PyUnicode_Check(cmd
)) {
664 PyErr_SetString(PyExc_TypeError
,
665 "eval() arg 1 must be a string or code object");
670 #ifdef Py_USING_UNICODE
671 if (PyUnicode_Check(cmd
)) {
672 tmp
= PyUnicode_AsUTF8String(cmd
);
676 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
679 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
683 while (*str
== ' ' || *str
== '\t')
686 (void)PyEval_MergeCompilerFlags(&cf
);
687 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
692 PyDoc_STRVAR(eval_doc
,
693 "eval(source[, globals[, locals]]) -> value\n\
695 Evaluate the source in the context of globals and locals.\n\
696 The source may be a string representing a Python expression\n\
697 or a code object as returned by compile().\n\
698 The globals must be a dictionary and locals can be any mapping,\n\
699 defaulting to the current globals and locals.\n\
700 If only globals is given, locals defaults to it.\n");
704 builtin_execfile(PyObject
*self
, PyObject
*args
)
707 PyObject
*globals
= Py_None
, *locals
= Py_None
;
713 if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
717 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
719 &PyDict_Type
, &globals
,
722 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
723 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
726 if (globals
== Py_None
) {
727 globals
= PyEval_GetGlobals();
728 if (locals
== Py_None
)
729 locals
= PyEval_GetLocals();
731 else if (locals
== Py_None
)
733 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
734 if (PyDict_SetItemString(globals
, "__builtins__",
735 PyEval_GetBuiltins()) != 0)
740 /* Test for existence or directory. */
745 if ((d
= dirstat(filename
))!=nil
) {
747 werrstr("is a directory");
753 #elif defined(RISCOS)
754 if (object_exists(filename
)) {
760 #else /* standard Posix */
763 if (stat(filename
, &s
) == 0) {
764 if (S_ISDIR(s
.st_mode
))
765 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
777 Py_BEGIN_ALLOW_THREADS
778 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
787 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
791 if (PyEval_MergeCompilerFlags(&cf
))
792 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
795 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
800 PyDoc_STRVAR(execfile_doc
,
801 "execfile(filename[, globals[, locals]])\n\
803 Read and execute a Python script from a file.\n\
804 The globals and locals are dictionaries, defaulting to the current\n\
805 globals and locals. If only globals is given, locals defaults to it.");
809 builtin_getattr(PyObject
*self
, PyObject
*args
)
811 PyObject
*v
, *result
, *dflt
= NULL
;
814 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
816 #ifdef Py_USING_UNICODE
817 if (PyUnicode_Check(name
)) {
818 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
824 if (!PyString_Check(name
)) {
825 PyErr_SetString(PyExc_TypeError
,
826 "getattr(): attribute name must be string");
829 result
= PyObject_GetAttr(v
, name
);
830 if (result
== NULL
&& dflt
!= NULL
&&
831 PyErr_ExceptionMatches(PyExc_AttributeError
))
840 PyDoc_STRVAR(getattr_doc
,
841 "getattr(object, name[, default]) -> value\n\
843 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
844 When a default argument is given, it is returned when the attribute doesn't\n\
845 exist; without it, an exception is raised in that case.");
849 builtin_globals(PyObject
*self
)
853 d
= PyEval_GetGlobals();
858 PyDoc_STRVAR(globals_doc
,
859 "globals() -> dictionary\n\
861 Return the dictionary containing the current scope's global variables.");
865 builtin_hasattr(PyObject
*self
, PyObject
*args
)
870 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
872 #ifdef Py_USING_UNICODE
873 if (PyUnicode_Check(name
)) {
874 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
880 if (!PyString_Check(name
)) {
881 PyErr_SetString(PyExc_TypeError
,
882 "hasattr(): attribute name must be string");
885 v
= PyObject_GetAttr(v
, name
);
887 if (!PyErr_ExceptionMatches(PyExc_Exception
))
900 PyDoc_STRVAR(hasattr_doc
,
901 "hasattr(object, name) -> bool\n\
903 Return whether the object has an attribute with the given name.\n\
904 (This is done by calling getattr(object, name) and catching exceptions.)");
908 builtin_id(PyObject
*self
, PyObject
*v
)
910 return PyLong_FromVoidPtr(v
);
914 "id(object) -> integer\n\
916 Return the identity of an object. This is guaranteed to be unique among\n\
917 simultaneously existing objects. (Hint: it's the object's memory address.)");
921 builtin_map(PyObject
*self
, PyObject
*args
)
924 PyObject
*it
; /* the iterator object */
925 int saw_StopIteration
; /* bool: did the iterator end? */
928 PyObject
*func
, *result
;
929 sequence
*seqs
= NULL
, *sqp
;
933 n
= PyTuple_Size(args
);
935 PyErr_SetString(PyExc_TypeError
,
936 "map() requires at least two args");
940 func
= PyTuple_GetItem(args
, 0);
943 if (func
== Py_None
) {
944 if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
945 "use list(...)", 1) < 0)
948 /* map(None, S) is the same as list(S). */
949 return PySequence_List(PyTuple_GetItem(args
, 1));
953 /* Get space for sequence descriptors. Must NULL out the iterator
954 * pointers so that jumping to Fail_2 later doesn't see trash.
956 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
960 for (i
= 0; i
< n
; ++i
) {
961 seqs
[i
].it
= (PyObject
*)NULL
;
962 seqs
[i
].saw_StopIteration
= 0;
965 /* Do a first pass to obtain iterators for the arguments, and set len
966 * to the largest of their lengths.
969 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
974 curseq
= PyTuple_GetItem(args
, i
+1);
975 sqp
->it
= PyObject_GetIter(curseq
);
976 if (sqp
->it
== NULL
) {
977 static char errmsg
[] =
978 "argument %d to map() must support iteration";
979 char errbuf
[sizeof(errmsg
) + 25];
980 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
981 PyErr_SetString(PyExc_TypeError
, errbuf
);
986 curlen
= _PyObject_LengthHint(curseq
, 8);
991 /* Get space for the result list. */
992 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
995 /* Iterate over the sequences until all have stopped. */
997 PyObject
*alist
, *item
=NULL
, *value
;
1000 if (func
== Py_None
&& n
== 1)
1002 else if ((alist
= PyTuple_New(n
)) == NULL
)
1005 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
1006 if (sqp
->saw_StopIteration
) {
1011 item
= PyIter_Next(sqp
->it
);
1015 if (PyErr_Occurred()) {
1021 sqp
->saw_StopIteration
= 1;
1025 PyTuple_SET_ITEM(alist
, j
, item
);
1033 if (numactive
== 0) {
1038 if (func
== Py_None
)
1041 value
= PyEval_CallObject(func
, alist
);
1047 int status
= PyList_Append(result
, value
);
1052 else if (PyList_SetItem(result
, i
, value
) < 0)
1056 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1067 for (i
= 0; i
< n
; ++i
)
1068 Py_XDECREF(seqs
[i
].it
);
1073 PyDoc_STRVAR(map_doc
,
1074 "map(function, sequence[, sequence, ...]) -> list\n\
1076 Return a list of the results of applying the function to the items of\n\
1077 the argument sequence(s). If more than one sequence is given, the\n\
1078 function is called with an argument list consisting of the corresponding\n\
1079 item of each sequence, substituting None for missing values when not all\n\
1080 sequences have the same length. If the function is None, return a list of\n\
1081 the items of the sequence (or a list of tuples if more than one sequence).");
1085 builtin_next(PyObject
*self
, PyObject
*args
)
1088 PyObject
*def
= NULL
;
1090 if (!PyArg_UnpackTuple(args
, "next", 1, 2, &it
, &def
))
1092 if (!PyIter_Check(it
)) {
1093 PyErr_Format(PyExc_TypeError
,
1094 "%.200s object is not an iterator",
1095 it
->ob_type
->tp_name
);
1099 res
= (*it
->ob_type
->tp_iternext
)(it
);
1102 } else if (def
!= NULL
) {
1103 if (PyErr_Occurred()) {
1104 if (!PyErr_ExceptionMatches(PyExc_StopIteration
))
1110 } else if (PyErr_Occurred()) {
1113 PyErr_SetNone(PyExc_StopIteration
);
1118 PyDoc_STRVAR(next_doc
,
1119 "next(iterator[, default])\n\
1121 Return the next item from the iterator. If default is given and the iterator\n\
1122 is exhausted, it is returned instead of raising StopIteration.");
1126 builtin_setattr(PyObject
*self
, PyObject
*args
)
1132 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1134 if (PyObject_SetAttr(v
, name
, value
) != 0)
1140 PyDoc_STRVAR(setattr_doc
,
1141 "setattr(object, name, value)\n\
1143 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1148 builtin_delattr(PyObject
*self
, PyObject
*args
)
1153 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1155 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1161 PyDoc_STRVAR(delattr_doc
,
1162 "delattr(object, name)\n\
1164 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1169 builtin_hash(PyObject
*self
, PyObject
*v
)
1173 x
= PyObject_Hash(v
);
1176 return PyInt_FromLong(x
);
1179 PyDoc_STRVAR(hash_doc
,
1180 "hash(object) -> integer\n\
1182 Return a hash value for the object. Two objects with the same value have\n\
1183 the same hash value. The reverse is not necessarily true, but likely.");
1187 builtin_hex(PyObject
*self
, PyObject
*v
)
1189 PyNumberMethods
*nb
;
1192 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1193 nb
->nb_hex
== NULL
) {
1194 PyErr_SetString(PyExc_TypeError
,
1195 "hex() argument can't be converted to hex");
1198 res
= (*nb
->nb_hex
)(v
);
1199 if (res
&& !PyString_Check(res
)) {
1200 PyErr_Format(PyExc_TypeError
,
1201 "__hex__ returned non-string (type %.200s)",
1202 res
->ob_type
->tp_name
);
1209 PyDoc_STRVAR(hex_doc
,
1210 "hex(number) -> string\n\
1212 Return the hexadecimal representation of an integer or long integer.");
1215 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1218 builtin_input(PyObject
*self
, PyObject
*args
)
1223 PyObject
*globals
, *locals
;
1226 line
= builtin_raw_input(self
, args
);
1229 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1231 while (*str
== ' ' || *str
== '\t')
1233 globals
= PyEval_GetGlobals();
1234 locals
= PyEval_GetLocals();
1235 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1236 if (PyDict_SetItemString(globals
, "__builtins__",
1237 PyEval_GetBuiltins()) != 0)
1241 PyEval_MergeCompilerFlags(&cf
);
1242 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1247 PyDoc_STRVAR(input_doc
,
1248 "input([prompt]) -> value\n\
1250 Equivalent to eval(raw_input(prompt)).");
1254 builtin_intern(PyObject
*self
, PyObject
*args
)
1257 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1259 if (!PyString_CheckExact(s
)) {
1260 PyErr_SetString(PyExc_TypeError
,
1261 "can't intern subclass of string");
1265 PyString_InternInPlace(&s
);
1269 PyDoc_STRVAR(intern_doc
,
1270 "intern(string) -> string\n\
1272 ``Intern'' the given string. This enters the string in the (global)\n\
1273 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1274 Return the string itself or the previously interned string object with the\n\
1279 builtin_iter(PyObject
*self
, PyObject
*args
)
1281 PyObject
*v
, *w
= NULL
;
1283 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1286 return PyObject_GetIter(v
);
1287 if (!PyCallable_Check(v
)) {
1288 PyErr_SetString(PyExc_TypeError
,
1289 "iter(v, w): v must be callable");
1292 return PyCallIter_New(v
, w
);
1295 PyDoc_STRVAR(iter_doc
,
1296 "iter(collection) -> iterator\n\
1297 iter(callable, sentinel) -> iterator\n\
1299 Get an iterator from an object. In the first form, the argument must\n\
1300 supply its own iterator, or be a sequence.\n\
1301 In the second form, the callable is called until it returns the sentinel.");
1305 builtin_len(PyObject
*self
, PyObject
*v
)
1309 res
= PyObject_Size(v
);
1310 if (res
< 0 && PyErr_Occurred())
1312 return PyInt_FromSsize_t(res
);
1315 PyDoc_STRVAR(len_doc
,
1316 "len(object) -> integer\n\
1318 Return the number of items of a sequence or mapping.");
1322 builtin_locals(PyObject
*self
)
1326 d
= PyEval_GetLocals();
1331 PyDoc_STRVAR(locals_doc
,
1332 "locals() -> dictionary\n\
1334 Update and return a dictionary containing the current scope's local variables.");
1338 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1340 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1341 const char *name
= op
== Py_LT
? "min" : "max";
1343 if (PyTuple_Size(args
) > 1)
1345 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1348 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1349 keyfunc
= PyDict_GetItemString(kwds
, "key");
1350 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1351 PyErr_Format(PyExc_TypeError
,
1352 "%s() got an unexpected keyword argument", name
);
1358 it
= PyObject_GetIter(v
);
1360 Py_XDECREF(keyfunc
);
1364 maxitem
= NULL
; /* the result */
1365 maxval
= NULL
; /* the value associated with the result */
1366 while (( item
= PyIter_Next(it
) )) {
1367 /* get the value from the key function */
1368 if (keyfunc
!= NULL
) {
1369 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1373 /* no key function; the value is the item */
1379 /* maximum value and item are unset; set them */
1380 if (maxval
== NULL
) {
1384 /* maximum value and item are set; update them as necessary */
1386 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1388 goto Fail_it_item_and_val
;
1401 if (PyErr_Occurred())
1403 if (maxval
== NULL
) {
1404 PyErr_Format(PyExc_ValueError
,
1405 "%s() arg is an empty sequence", name
);
1406 assert(maxitem
== NULL
);
1411 Py_XDECREF(keyfunc
);
1414 Fail_it_item_and_val
:
1420 Py_XDECREF(maxitem
);
1422 Py_XDECREF(keyfunc
);
1427 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1429 return min_max(args
, kwds
, Py_LT
);
1432 PyDoc_STRVAR(min_doc
,
1433 "min(iterable[, key=func]) -> value\n\
1434 min(a, b, c, ...[, key=func]) -> value\n\
1436 With a single iterable argument, return its smallest item.\n\
1437 With two or more arguments, return the smallest argument.");
1441 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1443 return min_max(args
, kwds
, Py_GT
);
1446 PyDoc_STRVAR(max_doc
,
1447 "max(iterable[, key=func]) -> value\n\
1448 max(a, b, c, ...[, key=func]) -> value\n\
1450 With a single iterable argument, return its largest item.\n\
1451 With two or more arguments, return the largest argument.");
1455 builtin_oct(PyObject
*self
, PyObject
*v
)
1457 PyNumberMethods
*nb
;
1460 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1461 nb
->nb_oct
== NULL
) {
1462 PyErr_SetString(PyExc_TypeError
,
1463 "oct() argument can't be converted to oct");
1466 res
= (*nb
->nb_oct
)(v
);
1467 if (res
&& !PyString_Check(res
)) {
1468 PyErr_Format(PyExc_TypeError
,
1469 "__oct__ returned non-string (type %.200s)",
1470 res
->ob_type
->tp_name
);
1477 PyDoc_STRVAR(oct_doc
,
1478 "oct(number) -> string\n\
1480 Return the octal representation of an integer or long integer.");
1484 builtin_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1486 return PyObject_Call((PyObject
*)&PyFile_Type
, args
, kwds
);
1489 PyDoc_STRVAR(open_doc
,
1490 "open(name[, mode[, buffering]]) -> file object\n\
1492 Open a file using the file() type, returns a file object. This is the\n\
1493 preferred way to open a file. See file.__doc__ for further information.");
1497 builtin_ord(PyObject
*self
, PyObject
* obj
)
1502 if (PyString_Check(obj
)) {
1503 size
= PyString_GET_SIZE(obj
);
1505 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1506 return PyInt_FromLong(ord
);
1508 } else if (PyByteArray_Check(obj
)) {
1509 size
= PyByteArray_GET_SIZE(obj
);
1511 ord
= (long)((unsigned char)*PyByteArray_AS_STRING(obj
));
1512 return PyInt_FromLong(ord
);
1515 #ifdef Py_USING_UNICODE
1516 } else if (PyUnicode_Check(obj
)) {
1517 size
= PyUnicode_GET_SIZE(obj
);
1519 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1520 return PyInt_FromLong(ord
);
1524 PyErr_Format(PyExc_TypeError
,
1525 "ord() expected string of length 1, but " \
1526 "%.200s found", obj
->ob_type
->tp_name
);
1530 PyErr_Format(PyExc_TypeError
,
1531 "ord() expected a character, "
1532 "but string of length %zd found",
1537 PyDoc_STRVAR(ord_doc
,
1538 "ord(c) -> integer\n\
1540 Return the integer ordinal of a one-character string.");
1544 builtin_pow(PyObject
*self
, PyObject
*args
)
1546 PyObject
*v
, *w
, *z
= Py_None
;
1548 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1550 return PyNumber_Power(v
, w
, z
);
1553 PyDoc_STRVAR(pow_doc
,
1554 "pow(x, y[, z]) -> number\n\
1556 With two arguments, equivalent to x**y. With three arguments,\n\
1557 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1561 builtin_print(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1563 static char *kwlist
[] = {"sep", "end", "file", 0};
1564 static PyObject
*dummy_args
= NULL
;
1565 static PyObject
*unicode_newline
= NULL
, *unicode_space
= NULL
;
1566 static PyObject
*str_newline
= NULL
, *str_space
= NULL
;
1567 PyObject
*newline
, *space
;
1568 PyObject
*sep
= NULL
, *end
= NULL
, *file
= NULL
;
1569 int i
, err
, use_unicode
= 0;
1571 if (dummy_args
== NULL
) {
1572 if (!(dummy_args
= PyTuple_New(0)))
1575 if (str_newline
== NULL
) {
1576 str_newline
= PyString_FromString("\n");
1577 if (str_newline
== NULL
)
1579 str_space
= PyString_FromString(" ");
1580 if (str_space
== NULL
) {
1581 Py_CLEAR(str_newline
);
1584 unicode_newline
= PyUnicode_FromString("\n");
1585 if (unicode_newline
== NULL
) {
1586 Py_CLEAR(str_newline
);
1587 Py_CLEAR(str_space
);
1590 unicode_space
= PyUnicode_FromString(" ");
1591 if (unicode_space
== NULL
) {
1592 Py_CLEAR(str_newline
);
1593 Py_CLEAR(str_space
);
1594 Py_CLEAR(unicode_space
);
1598 if (!PyArg_ParseTupleAndKeywords(dummy_args
, kwds
, "|OOO:print",
1599 kwlist
, &sep
, &end
, &file
))
1601 if (file
== NULL
|| file
== Py_None
) {
1602 file
= PySys_GetObject("stdout");
1603 /* sys.stdout may be None when FILE* stdout isn't connected */
1604 if (file
== Py_None
)
1607 if (sep
== Py_None
) {
1611 if (PyUnicode_Check(sep
)) {
1614 else if (!PyString_Check(sep
)) {
1615 PyErr_Format(PyExc_TypeError
,
1616 "sep must be None, str or unicode, not %.200s",
1617 sep
->ob_type
->tp_name
);
1624 if (PyUnicode_Check(end
)) {
1627 else if (!PyString_Check(end
)) {
1628 PyErr_Format(PyExc_TypeError
,
1629 "end must be None, str or unicode, not %.200s",
1630 end
->ob_type
->tp_name
);
1636 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1637 if (PyUnicode_Check(PyTuple_GET_ITEM(args
, i
))) {
1644 newline
= unicode_newline
;
1645 space
= unicode_space
;
1648 newline
= str_newline
;
1652 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1655 err
= PyFile_WriteObject(space
, file
,
1658 err
= PyFile_WriteObject(sep
, file
,
1663 err
= PyFile_WriteObject(PyTuple_GetItem(args
, i
), file
,
1670 err
= PyFile_WriteObject(newline
, file
, Py_PRINT_RAW
);
1672 err
= PyFile_WriteObject(end
, file
, Py_PRINT_RAW
);
1679 PyDoc_STRVAR(print_doc
,
1680 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1682 Prints the values to a stream, or to sys.stdout by default.\n\
1683 Optional keyword arguments:\n\
1684 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1685 sep: string inserted between values, default a space.\n\
1686 end: string appended after the last value, default a newline.");
1689 /* Return number of items in range (lo, hi, step), when arguments are
1690 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1691 * & only if the true value is too large to fit in a signed long.
1692 * Arguments MUST return 1 with either PyInt_Check() or
1693 * PyLong_Check(). Return -1 when there is an error.
1696 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1698 /* -------------------------------------------------------------
1699 Algorithm is equal to that of get_len_of_range(), but it operates
1700 on PyObjects (which are assumed to be PyLong or PyInt objects).
1701 ---------------------------------------------------------------*/
1703 PyObject
*diff
= NULL
;
1704 PyObject
*one
= NULL
;
1705 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1706 /* holds sub-expression evaluations */
1708 /* if (lo >= hi), return length of 0. */
1709 if (PyObject_Compare(lo
, hi
) >= 0)
1712 if ((one
= PyLong_FromLong(1L)) == NULL
)
1715 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1718 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1721 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1724 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1727 n
= PyLong_AsLong(tmp3
);
1728 if (PyErr_Occurred()) { /* Check for Overflow */
1749 /* Helper function for handle_range_longs. If arg is int or long
1750 object, returns it with incremented reference count. If arg is
1751 float, raises type error. As a last resort, creates a new int by
1752 calling arg type's nb_int method if it is defined. Returns NULL
1753 and sets exception on error.
1755 Returns a new reference to an int object. */
1757 get_range_long_argument(PyObject
*arg
, const char *name
)
1760 PyNumberMethods
*nb
;
1761 if (PyInt_Check(arg
) || PyLong_Check(arg
)) {
1765 if (PyFloat_Check(arg
) ||
1766 (nb
= Py_TYPE(arg
)->tp_as_number
) == NULL
||
1767 nb
->nb_int
== NULL
) {
1768 PyErr_Format(PyExc_TypeError
,
1769 "range() integer %s argument expected, got %s.",
1770 name
, arg
->ob_type
->tp_name
);
1773 v
= nb
->nb_int(arg
);
1776 if (PyInt_Check(v
) || PyLong_Check(v
))
1779 PyErr_SetString(PyExc_TypeError
,
1780 "__int__ should return int object");
1784 /* An extension of builtin_range() that handles the case when PyLong
1785 * arguments are given. */
1787 handle_range_longs(PyObject
*self
, PyObject
*args
)
1789 PyObject
*ilow
= NULL
;
1790 PyObject
*ihigh
= NULL
;
1791 PyObject
*istep
= NULL
;
1793 PyObject
*low
= NULL
;
1794 PyObject
*high
= NULL
;
1795 PyObject
*step
= NULL
;
1797 PyObject
*curnum
= NULL
;
1803 PyObject
*zero
= PyLong_FromLong(0);
1808 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1813 /* Figure out which way we were called, supply defaults, and be
1814 * sure to incref everything so that the decrefs at the end
1815 * are correct. NB: ilow, ihigh and istep are borrowed references.
1817 assert(ilow
!= NULL
);
1818 if (ihigh
== NULL
) {
1819 /* only 1 arg -- it's the upper limit */
1824 /* convert ihigh if necessary */
1825 assert(ihigh
!= NULL
);
1826 high
= get_range_long_argument(ihigh
, "end");
1830 /* ihigh correct now; do ilow */
1836 low
= get_range_long_argument(ilow
, "start");
1841 /* ilow and ihigh correct now; do istep */
1843 step
= PyLong_FromLong(1);
1845 step
= get_range_long_argument(istep
, "step");
1849 if (PyObject_Cmp(step
, zero
, &cmp_result
) == -1)
1852 if (cmp_result
== 0) {
1853 PyErr_SetString(PyExc_ValueError
,
1854 "range() step argument must not be zero");
1859 bign
= get_len_of_range_longs(low
, high
, step
);
1861 PyObject
*neg_step
= PyNumber_Negative(step
);
1862 if (neg_step
== NULL
)
1864 bign
= get_len_of_range_longs(high
, low
, neg_step
);
1865 Py_DECREF(neg_step
);
1868 n
= (Py_ssize_t
)bign
;
1869 if (bign
< 0 || (long)n
!= bign
) {
1870 PyErr_SetString(PyExc_OverflowError
,
1871 "range() result has too many items");
1882 for (i
= 0; i
< n
; i
++) {
1883 PyObject
*w
= PyNumber_Long(curnum
);
1888 PyList_SET_ITEM(v
, i
, w
);
1890 tmp_num
= PyNumber_Add(curnum
, step
);
1891 if (tmp_num
== NULL
)
1914 /* Return number of items in range/xrange (lo, hi, step). step > 0
1915 * required. Return a value < 0 if & only if the true value is too
1916 * large to fit in a signed long.
1919 get_len_of_range(long lo
, long hi
, long step
)
1921 /* -------------------------------------------------------------
1922 If lo >= hi, the range is empty.
1923 Else if n values are in the range, the last one is
1924 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1925 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1926 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1927 the RHS is non-negative and so truncation is the same as the
1928 floor. Letting M be the largest positive long, the worst case
1929 for the RHS numerator is hi=M, lo=-M-1, and then
1930 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1931 precision to compute the RHS exactly.
1932 ---------------------------------------------------------------*/
1935 unsigned long uhi
= (unsigned long)hi
;
1936 unsigned long ulo
= (unsigned long)lo
;
1937 unsigned long diff
= uhi
- ulo
- 1;
1938 n
= (long)(diff
/ (unsigned long)step
+ 1);
1944 builtin_range(PyObject
*self
, PyObject
*args
)
1946 long ilow
= 0, ihigh
= 0, istep
= 1;
1952 if (PyTuple_Size(args
) <= 1) {
1953 if (!PyArg_ParseTuple(args
,
1954 "l;range() requires 1-3 int arguments",
1957 return handle_range_longs(self
, args
);
1961 if (!PyArg_ParseTuple(args
,
1962 "ll|l;range() requires 1-3 int arguments",
1963 &ilow
, &ihigh
, &istep
)) {
1965 return handle_range_longs(self
, args
);
1969 PyErr_SetString(PyExc_ValueError
,
1970 "range() step argument must not be zero");
1974 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1976 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1977 n
= (Py_ssize_t
)bign
;
1978 if (bign
< 0 || (long)n
!= bign
) {
1979 PyErr_SetString(PyExc_OverflowError
,
1980 "range() result has too many items");
1986 for (i
= 0; i
< n
; i
++) {
1987 PyObject
*w
= PyInt_FromLong(ilow
);
1992 PyList_SET_ITEM(v
, i
, w
);
1998 PyDoc_STRVAR(range_doc
,
1999 "range([start,] stop[, step]) -> list of integers\n\
2001 Return a list containing an arithmetic progression of integers.\n\
2002 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
2003 When step is given, it specifies the increment (or decrement).\n\
2004 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
2005 These are exactly the valid indices for a list of 4 elements.");
2009 builtin_raw_input(PyObject
*self
, PyObject
*args
)
2012 PyObject
*fin
= PySys_GetObject("stdin");
2013 PyObject
*fout
= PySys_GetObject("stdout");
2015 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
2019 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
2023 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
2026 if (PyFile_SoftSpace(fout
, 0)) {
2027 if (PyFile_WriteString(" ", fout
) != 0)
2030 if (PyFile_AsFile(fin
) && PyFile_AsFile(fout
)
2031 && isatty(fileno(PyFile_AsFile(fin
)))
2032 && isatty(fileno(PyFile_AsFile(fout
)))) {
2038 po
= PyObject_Str(v
);
2041 prompt
= PyString_AsString(po
);
2049 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
2053 if (!PyErr_Occurred())
2054 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2058 PyErr_SetNone(PyExc_EOFError
);
2061 else { /* strip trailing '\n' */
2062 size_t len
= strlen(s
);
2063 if (len
> PY_SSIZE_T_MAX
) {
2064 PyErr_SetString(PyExc_OverflowError
,
2065 "[raw_]input: input too long");
2069 result
= PyString_FromStringAndSize(s
, len
-1);
2076 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
2079 return PyFile_GetLine(fin
, -1);
2082 PyDoc_STRVAR(raw_input_doc
,
2083 "raw_input([prompt]) -> string\n\
2085 Read a string from standard input. The trailing newline is stripped.\n\
2086 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
2087 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
2088 is printed without a trailing newline before reading.");
2092 builtin_reduce(PyObject
*self
, PyObject
*args
)
2094 static PyObject
*functools_reduce
= NULL
;
2096 if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
2097 "use functools.reduce()", 1) < 0)
2100 if (functools_reduce
== NULL
) {
2101 PyObject
*functools
= PyImport_ImportModule("functools");
2102 if (functools
== NULL
)
2104 functools_reduce
= PyObject_GetAttrString(functools
, "reduce");
2105 Py_DECREF(functools
);
2106 if (functools_reduce
== NULL
)
2109 return PyObject_Call(functools_reduce
, args
, NULL
);
2112 PyDoc_STRVAR(reduce_doc
,
2113 "reduce(function, sequence[, initial]) -> value\n\
2115 Apply a function of two arguments cumulatively to the items of a sequence,\n\
2116 from left to right, so as to reduce the sequence to a single value.\n\
2117 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
2118 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
2119 of the sequence in the calculation, and serves as a default when the\n\
2120 sequence is empty.");
2124 builtin_reload(PyObject
*self
, PyObject
*v
)
2126 if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
2130 return PyImport_ReloadModule(v
);
2133 PyDoc_STRVAR(reload_doc
,
2134 "reload(module) -> module\n\
2136 Reload the module. The module must have been successfully imported before.");
2140 builtin_repr(PyObject
*self
, PyObject
*v
)
2142 return PyObject_Repr(v
);
2145 PyDoc_STRVAR(repr_doc
,
2146 "repr(object) -> string\n\
2148 Return the canonical string representation of the object.\n\
2149 For most object types, eval(repr(object)) == object.");
2153 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2156 PyObject
*o_ndigits
= NULL
;
2158 static char *kwlist
[] = {"number", "ndigits", 0};
2160 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "d|O:round",
2161 kwlist
, &x
, &o_ndigits
))
2164 if (o_ndigits
== NULL
) {
2165 /* second argument defaults to 0 */
2169 /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
2170 ndigits
= PyNumber_AsSsize_t(o_ndigits
, NULL
);
2171 if (ndigits
== -1 && PyErr_Occurred())
2175 /* nans, infinities and zeros round to themselves */
2176 if (!Py_IS_FINITE(x
) || x
== 0.0)
2177 return PyFloat_FromDouble(x
);
2179 /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
2180 always rounds to itself. For ndigits < NDIGITS_MIN, x always
2181 rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
2182 #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
2183 #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
2184 if (ndigits
> NDIGITS_MAX
)
2186 return PyFloat_FromDouble(x
);
2187 else if (ndigits
< NDIGITS_MIN
)
2188 /* return 0.0, but with sign of x */
2189 return PyFloat_FromDouble(0.0*x
);
2191 /* finite x, and ndigits is not unreasonably large */
2192 /* _Py_double_round is defined in floatobject.c */
2193 return _Py_double_round(x
, (int)ndigits
);
2198 PyDoc_STRVAR(round_doc
,
2199 "round(number[, ndigits]) -> floating point number\n\
2201 Round a number to a given precision in decimal digits (default 0 digits).\n\
2202 This always returns a floating point number. Precision may be negative.");
2205 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2207 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
2209 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
2212 /* args 1-4 should match listsort in Objects/listobject.c */
2213 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
2214 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
2217 newlist
= PySequence_List(seq
);
2218 if (newlist
== NULL
)
2221 callable
= PyObject_GetAttrString(newlist
, "sort");
2222 if (callable
== NULL
) {
2227 newargs
= PyTuple_GetSlice(args
, 1, 4);
2228 if (newargs
== NULL
) {
2230 Py_DECREF(callable
);
2234 v
= PyObject_Call(callable
, newargs
, kwds
);
2236 Py_DECREF(callable
);
2245 PyDoc_STRVAR(sorted_doc
,
2246 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2249 builtin_vars(PyObject
*self
, PyObject
*args
)
2254 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
2257 d
= PyEval_GetLocals();
2259 if (!PyErr_Occurred())
2260 PyErr_SetString(PyExc_SystemError
,
2261 "vars(): no locals!?");
2267 d
= PyObject_GetAttrString(v
, "__dict__");
2269 PyErr_SetString(PyExc_TypeError
,
2270 "vars() argument must have __dict__ attribute");
2277 PyDoc_STRVAR(vars_doc
,
2278 "vars([object]) -> dictionary\n\
2280 Without arguments, equivalent to locals().\n\
2281 With an argument, equivalent to object.__dict__.");
2285 builtin_sum(PyObject
*self
, PyObject
*args
)
2288 PyObject
*result
= NULL
;
2289 PyObject
*temp
, *item
, *iter
;
2291 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
2294 iter
= PyObject_GetIter(seq
);
2298 if (result
== NULL
) {
2299 result
= PyInt_FromLong(0);
2300 if (result
== NULL
) {
2305 /* reject string values for 'start' parameter */
2306 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2307 PyErr_SetString(PyExc_TypeError
,
2308 "sum() can't sum strings [use ''.join(seq) instead]");
2316 /* Fast addition by keeping temporary sums in C instead of new Python objects.
2317 Assumes all inputs are the same type. If the assumption fails, default
2318 to the more general routine.
2320 if (PyInt_CheckExact(result
)) {
2321 long i_result
= PyInt_AS_LONG(result
);
2324 while(result
== NULL
) {
2325 item
= PyIter_Next(iter
);
2328 if (PyErr_Occurred())
2330 return PyInt_FromLong(i_result
);
2332 if (PyInt_CheckExact(item
)) {
2333 long b
= PyInt_AS_LONG(item
);
2334 long x
= i_result
+ b
;
2335 if ((x
^i_result
) >= 0 || (x
^b
) >= 0) {
2341 /* Either overflowed or is not an int. Restore real objects and process normally */
2342 result
= PyInt_FromLong(i_result
);
2343 temp
= PyNumber_Add(result
, item
);
2347 if (result
== NULL
) {
2354 if (PyFloat_CheckExact(result
)) {
2355 double f_result
= PyFloat_AS_DOUBLE(result
);
2358 while(result
== NULL
) {
2359 item
= PyIter_Next(iter
);
2362 if (PyErr_Occurred())
2364 return PyFloat_FromDouble(f_result
);
2366 if (PyFloat_CheckExact(item
)) {
2367 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2368 f_result
+= PyFloat_AS_DOUBLE(item
);
2369 PyFPE_END_PROTECT(f_result
)
2373 if (PyInt_CheckExact(item
)) {
2374 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
2375 f_result
+= (double)PyInt_AS_LONG(item
);
2376 PyFPE_END_PROTECT(f_result
)
2380 result
= PyFloat_FromDouble(f_result
);
2381 temp
= PyNumber_Add(result
, item
);
2385 if (result
== NULL
) {
2394 item
= PyIter_Next(iter
);
2396 /* error, or end-of-sequence */
2397 if (PyErr_Occurred()) {
2403 /* It's tempting to use PyNumber_InPlaceAdd instead of
2404 PyNumber_Add here, to avoid quadratic running time
2405 when doing 'sum(list_of_lists, [])'. However, this
2406 would produce a change in behaviour: a snippet like
2409 sum([[x] for x in range(10)], empty)
2411 would change the value of empty. */
2412 temp
= PyNumber_Add(result
, item
);
2423 PyDoc_STRVAR(sum_doc
,
2424 "sum(sequence[, start]) -> value\n\
2426 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2427 of parameter 'start' (which defaults to 0). When the sequence is\n\
2428 empty, returns start.");
2432 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2438 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2441 retval
= PyObject_IsInstance(inst
, cls
);
2444 return PyBool_FromLong(retval
);
2447 PyDoc_STRVAR(isinstance_doc
,
2448 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2450 Return whether an object is an instance of a class or of a subclass thereof.\n\
2451 With a type as second argument, return whether that is the object's type.\n\
2452 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2453 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2457 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2463 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2466 retval
= PyObject_IsSubclass(derived
, cls
);
2469 return PyBool_FromLong(retval
);
2472 PyDoc_STRVAR(issubclass_doc
,
2473 "issubclass(C, B) -> bool\n\
2475 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2476 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2477 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2481 builtin_zip(PyObject
*self
, PyObject
*args
)
2484 const Py_ssize_t itemsize
= PySequence_Length(args
);
2486 PyObject
*itlist
; /* tuple of iterators */
2487 Py_ssize_t len
; /* guess at result length */
2490 return PyList_New(0);
2492 /* args must be a tuple */
2493 assert(PyTuple_Check(args
));
2495 /* Guess at result length: the shortest of the input lengths.
2496 If some argument refuses to say, we refuse to guess too, lest
2497 an argument like xrange(sys.maxint) lead us astray.*/
2498 len
= -1; /* unknown */
2499 for (i
= 0; i
< itemsize
; ++i
) {
2500 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2501 Py_ssize_t thislen
= _PyObject_LengthHint(item
, -2);
2508 else if (len
< 0 || thislen
< len
)
2512 /* allocate result list */
2514 len
= 10; /* arbitrary */
2515 if ((ret
= PyList_New(len
)) == NULL
)
2518 /* obtain iterators */
2519 itlist
= PyTuple_New(itemsize
);
2522 for (i
= 0; i
< itemsize
; ++i
) {
2523 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2524 PyObject
*it
= PyObject_GetIter(item
);
2526 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2527 PyErr_Format(PyExc_TypeError
,
2528 "zip argument #%zd must support iteration",
2530 goto Fail_ret_itlist
;
2532 PyTuple_SET_ITEM(itlist
, i
, it
);
2535 /* build result into ret list */
2536 for (i
= 0; ; ++i
) {
2538 PyObject
*next
= PyTuple_New(itemsize
);
2540 goto Fail_ret_itlist
;
2542 for (j
= 0; j
< itemsize
; j
++) {
2543 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2544 PyObject
*item
= PyIter_Next(it
);
2546 if (PyErr_Occurred()) {
2554 PyTuple_SET_ITEM(next
, j
, item
);
2558 PyList_SET_ITEM(ret
, i
, next
);
2560 int status
= PyList_Append(ret
, next
);
2564 goto Fail_ret_itlist
;
2569 if (ret
!= NULL
&& i
< len
) {
2570 /* The list is too big. */
2571 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2584 PyDoc_STRVAR(zip_doc
,
2585 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2587 Return a list of tuples, where each tuple contains the i-th element\n\
2588 from each of the argument sequences. The returned list is truncated\n\
2589 in length to the length of the shortest argument sequence.");
2592 static PyMethodDef builtin_methods
[] = {
2593 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2594 {"abs", builtin_abs
, METH_O
, abs_doc
},
2595 {"all", builtin_all
, METH_O
, all_doc
},
2596 {"any", builtin_any
, METH_O
, any_doc
},
2597 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2598 {"bin", builtin_bin
, METH_O
, bin_doc
},
2599 {"callable", builtin_callable
, METH_O
, callable_doc
},
2600 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2601 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2602 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2603 {"compile", (PyCFunction
)builtin_compile
, METH_VARARGS
| METH_KEYWORDS
, compile_doc
},
2604 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2605 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2606 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2607 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2608 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2609 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2610 {"format", builtin_format
, METH_VARARGS
, format_doc
},
2611 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2612 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2613 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2614 {"hash", builtin_hash
, METH_O
, hash_doc
},
2615 {"hex", builtin_hex
, METH_O
, hex_doc
},
2616 {"id", builtin_id
, METH_O
, id_doc
},
2617 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2618 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2619 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2620 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2621 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2622 {"len", builtin_len
, METH_O
, len_doc
},
2623 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2624 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2625 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2626 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2627 {"next", builtin_next
, METH_VARARGS
, next_doc
},
2628 {"oct", builtin_oct
, METH_O
, oct_doc
},
2629 {"open", (PyCFunction
)builtin_open
, METH_VARARGS
| METH_KEYWORDS
, open_doc
},
2630 {"ord", builtin_ord
, METH_O
, ord_doc
},
2631 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2632 {"print", (PyCFunction
)builtin_print
, METH_VARARGS
| METH_KEYWORDS
, print_doc
},
2633 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2634 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2635 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2636 {"reload", builtin_reload
, METH_O
, reload_doc
},
2637 {"repr", builtin_repr
, METH_O
, repr_doc
},
2638 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2639 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2640 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2641 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2642 #ifdef Py_USING_UNICODE
2643 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2645 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2646 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2650 PyDoc_STRVAR(builtin_doc
,
2651 "Built-in functions, exceptions, and other objects.\n\
2653 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2656 _PyBuiltin_Init(void)
2658 PyObject
*mod
, *dict
, *debug
;
2659 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2660 builtin_doc
, (PyObject
*)NULL
,
2661 PYTHON_API_VERSION
);
2664 dict
= PyModule_GetDict(mod
);
2666 #ifdef Py_TRACE_REFS
2667 /* __builtin__ exposes a number of statically allocated objects
2668 * that, before this code was added in 2.3, never showed up in
2669 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2670 * result, programs leaking references to None and False (etc)
2671 * couldn't be diagnosed by examining sys.getobjects(0).
2673 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2675 #define ADD_TO_ALL(OBJECT) (void)0
2678 #define SETBUILTIN(NAME, OBJECT) \
2679 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2683 SETBUILTIN("None", Py_None
);
2684 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2685 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2686 SETBUILTIN("False", Py_False
);
2687 SETBUILTIN("True", Py_True
);
2688 SETBUILTIN("basestring", &PyBaseString_Type
);
2689 SETBUILTIN("bool", &PyBool_Type
);
2690 SETBUILTIN("memoryview", &PyMemoryView_Type
);
2691 SETBUILTIN("bytearray", &PyByteArray_Type
);
2692 SETBUILTIN("bytes", &PyString_Type
);
2693 SETBUILTIN("buffer", &PyBuffer_Type
);
2694 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2695 #ifndef WITHOUT_COMPLEX
2696 SETBUILTIN("complex", &PyComplex_Type
);
2698 SETBUILTIN("dict", &PyDict_Type
);
2699 SETBUILTIN("enumerate", &PyEnum_Type
);
2700 SETBUILTIN("file", &PyFile_Type
);
2701 SETBUILTIN("float", &PyFloat_Type
);
2702 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2703 SETBUILTIN("property", &PyProperty_Type
);
2704 SETBUILTIN("int", &PyInt_Type
);
2705 SETBUILTIN("list", &PyList_Type
);
2706 SETBUILTIN("long", &PyLong_Type
);
2707 SETBUILTIN("object", &PyBaseObject_Type
);
2708 SETBUILTIN("reversed", &PyReversed_Type
);
2709 SETBUILTIN("set", &PySet_Type
);
2710 SETBUILTIN("slice", &PySlice_Type
);
2711 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2712 SETBUILTIN("str", &PyString_Type
);
2713 SETBUILTIN("super", &PySuper_Type
);
2714 SETBUILTIN("tuple", &PyTuple_Type
);
2715 SETBUILTIN("type", &PyType_Type
);
2716 SETBUILTIN("xrange", &PyRange_Type
);
2717 #ifdef Py_USING_UNICODE
2718 SETBUILTIN("unicode", &PyUnicode_Type
);
2720 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2721 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2732 /* Helper for filter(): filter a tuple through a function */
2735 filtertuple(PyObject
*func
, PyObject
*tuple
)
2739 Py_ssize_t len
= PyTuple_Size(tuple
);
2742 if (PyTuple_CheckExact(tuple
))
2745 tuple
= PyTuple_New(0);
2749 if ((result
= PyTuple_New(len
)) == NULL
)
2752 for (i
= j
= 0; i
< len
; ++i
) {
2753 PyObject
*item
, *good
;
2756 if (tuple
->ob_type
->tp_as_sequence
&&
2757 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2758 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2762 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2765 if (func
== Py_None
) {
2770 PyObject
*arg
= PyTuple_Pack(1, item
);
2775 good
= PyEval_CallObject(func
, arg
);
2782 ok
= PyObject_IsTrue(good
);
2785 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2792 if (_PyTuple_Resize(&result
, j
) < 0)
2803 /* Helper for filter(): filter a string through a function */
2806 filterstring(PyObject
*func
, PyObject
*strobj
)
2810 Py_ssize_t len
= PyString_Size(strobj
);
2811 Py_ssize_t outlen
= len
;
2813 if (func
== Py_None
) {
2814 /* If it's a real string we can return the original,
2815 * as no character is ever false and __getitem__
2816 * does return this character. If it's a subclass
2817 * we must go through the __getitem__ loop */
2818 if (PyString_CheckExact(strobj
)) {
2823 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2826 for (i
= j
= 0; i
< len
; ++i
) {
2830 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2833 if (func
==Py_None
) {
2836 PyObject
*arg
, *good
;
2837 arg
= PyTuple_Pack(1, item
);
2842 good
= PyEval_CallObject(func
, arg
);
2848 ok
= PyObject_IsTrue(good
);
2853 if (!PyString_Check(item
)) {
2854 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2855 " __getitem__ returned different type");
2859 reslen
= PyString_GET_SIZE(item
);
2861 PyString_AS_STRING(result
)[j
++] =
2862 PyString_AS_STRING(item
)[0];
2864 /* do we need more space? */
2865 Py_ssize_t need
= j
;
2867 /* calculate space requirements while checking for overflow */
2868 if (need
> PY_SSIZE_T_MAX
- reslen
) {
2875 if (need
> PY_SSIZE_T_MAX
- len
) {
2887 need
= need
- i
- 1;
2890 assert(outlen
>= 0);
2892 if (need
> outlen
) {
2893 /* overallocate, to avoid reallocations */
2894 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
2899 if (need
<2*outlen
) {
2902 if (_PyString_Resize(&result
, need
)) {
2909 PyString_AS_STRING(result
) + j
,
2910 PyString_AS_STRING(item
),
2920 _PyString_Resize(&result
, j
);
2929 #ifdef Py_USING_UNICODE
2930 /* Helper for filter(): filter a Unicode object through a function */
2933 filterunicode(PyObject
*func
, PyObject
*strobj
)
2936 register Py_ssize_t i
, j
;
2937 Py_ssize_t len
= PyUnicode_GetSize(strobj
);
2938 Py_ssize_t outlen
= len
;
2940 if (func
== Py_None
) {
2941 /* If it's a real string we can return the original,
2942 * as no character is ever false and __getitem__
2943 * does return this character. If it's a subclass
2944 * we must go through the __getitem__ loop */
2945 if (PyUnicode_CheckExact(strobj
)) {
2950 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2953 for (i
= j
= 0; i
< len
; ++i
) {
2954 PyObject
*item
, *arg
, *good
;
2957 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2960 if (func
== Py_None
) {
2963 arg
= PyTuple_Pack(1, item
);
2968 good
= PyEval_CallObject(func
, arg
);
2974 ok
= PyObject_IsTrue(good
);
2979 if (!PyUnicode_Check(item
)) {
2980 PyErr_SetString(PyExc_TypeError
,
2981 "can't filter unicode to unicode:"
2982 " __getitem__ returned different type");
2986 reslen
= PyUnicode_GET_SIZE(item
);
2988 PyUnicode_AS_UNICODE(result
)[j
++] =
2989 PyUnicode_AS_UNICODE(item
)[0];
2991 /* do we need more space? */
2992 Py_ssize_t need
= j
+ reslen
+ len
- i
- 1;
2994 /* check that didnt overflow */
2995 if ((j
> PY_SSIZE_T_MAX
- reslen
) ||
2996 ((j
+ reslen
) > PY_SSIZE_T_MAX
- len
) ||
2997 ((j
+ reslen
+ len
) < i
) ||
2998 ((j
+ reslen
+ len
- i
) <= 0)) {
3004 assert(outlen
>= 0);
3006 if (need
> outlen
) {
3008 to avoid reallocations */
3009 if (need
< 2 * outlen
) {
3010 if (outlen
> PY_SSIZE_T_MAX
/ 2) {
3018 if (PyUnicode_Resize(
3019 &result
, need
) < 0) {
3025 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
3026 PyUnicode_AS_UNICODE(item
),
3027 reslen
*sizeof(Py_UNICODE
));
3035 PyUnicode_Resize(&result
, j
);