2 /* Built-in functions */
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_WIN32) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding
= "mbcs";
22 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
26 static PyObject
*filterstring(PyObject
*, PyObject
*);
27 static PyObject
*filtertuple (PyObject
*, PyObject
*);
30 builtin___import__(PyObject
*self
, PyObject
*args
)
33 PyObject
*globals
= NULL
;
34 PyObject
*locals
= NULL
;
35 PyObject
*fromlist
= NULL
;
37 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
38 &name
, &globals
, &locals
, &fromlist
))
40 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
43 static char import_doc
[] =
44 "__import__(name, globals, locals, fromlist) -> module\n\
46 Import a module. The globals are only used to determine the context;\n\
47 they are not modified. The locals are currently unused. The fromlist\n\
48 should be a list of names to emulate ``from name import ...'', or an\n\
49 empty list to emulate ``import name''.\n\
50 When importing a module from a package, note that __import__('A.B', ...)\n\
51 returns package A when fromlist is empty, but its submodule B when\n\
52 fromlist is not empty.";
56 builtin_abs(PyObject
*self
, PyObject
*v
)
58 return PyNumber_Absolute(v
);
61 static char abs_doc
[] =
62 "abs(number) -> number\n\
64 Return the absolute value of the argument.";
68 builtin_apply(PyObject
*self
, PyObject
*args
)
70 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
71 PyObject
*t
= NULL
, *retval
= NULL
;
73 if (!PyArg_ParseTuple(args
, "O|OO:apply", &func
, &alist
, &kwdict
))
76 if (!PyTuple_Check(alist
)) {
77 if (!PySequence_Check(alist
)) {
78 PyErr_Format(PyExc_TypeError
,
79 "apply() arg 2 expect sequence, found %s",
80 alist
->ob_type
->tp_name
);
83 t
= PySequence_Tuple(alist
);
89 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
90 PyErr_Format(PyExc_TypeError
,
91 "apply() arg 3 expected dictionary, found %s",
92 kwdict
->ob_type
->tp_name
);
95 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
101 static char apply_doc
[] =
102 "apply(object[, args[, kwargs]]) -> value\n\
104 Call a callable object with positional arguments taken from the tuple args,\n\
105 and keyword arguments taken from the optional dictionary kwargs.\n\
106 Note that classes are callable, as are instances with a __call__() method.";
110 builtin_buffer(PyObject
*self
, PyObject
*args
)
114 int size
= Py_END_OF_BUFFER
;
116 if ( !PyArg_ParseTuple(args
, "O|ii:buffer", &ob
, &offset
, &size
) )
118 return PyBuffer_FromObject(ob
, offset
, size
);
121 static char buffer_doc
[] =
122 "buffer(object [, offset[, size]]) -> object\n\
124 Create a new buffer object which references the given object.\n\
125 The buffer will reference a slice of the target object from the\n\
126 start of the object (or at the specified offset). The slice will\n\
127 extend to the end of the target object (or with the specified size).";
131 builtin_callable(PyObject
*self
, PyObject
*v
)
133 return PyInt_FromLong((long)PyCallable_Check(v
));
136 static char callable_doc
[] =
137 "callable(object) -> Boolean\n\
139 Return whether the object is callable (i.e., some kind of function).\n\
140 Note that classes are callable, as are instances with a __call__() method.";
144 builtin_filter(PyObject
*self
, PyObject
*args
)
146 PyObject
*func
, *seq
, *result
, *it
;
147 int len
; /* guess for result list size */
150 if (!PyArg_ParseTuple(args
, "OO:filter", &func
, &seq
))
153 /* Strings and tuples return a result of the same type. */
154 if (PyString_Check(seq
))
155 return filterstring(func
, seq
);
156 if (PyTuple_Check(seq
))
157 return filtertuple(func
, seq
);
160 it
= PyObject_GetIter(seq
);
164 /* Guess a result list size. */
165 len
= -1; /* unknown */
166 if (PySequence_Check(seq
) &&
167 seq
->ob_type
->tp_as_sequence
->sq_length
) {
168 len
= PySequence_Size(seq
);
173 len
= 8; /* arbitrary */
175 /* Get a result list. */
176 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
177 /* Eww - can modify the list in-place. */
182 result
= PyList_New(len
);
187 /* Build the result list. */
190 PyObject
*item
, *good
;
193 item
= PyIter_Next(it
);
195 if (PyErr_Occurred())
200 if (func
== Py_None
) {
205 PyObject
*arg
= Py_BuildValue("(O)", item
);
210 good
= PyEval_CallObject(func
, arg
);
217 ok
= PyObject_IsTrue(good
);
221 PyList_SET_ITEM(result
, j
, item
);
223 int status
= PyList_Append(result
, item
);
235 /* Cut back result list if len is too big. */
236 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
249 static char filter_doc
[] =
250 "filter(function, sequence) -> list\n\
252 Return a list containing those items of sequence for which function(item)\n\
253 is true. If function is None, return a list of items that are true.";
257 builtin_chr(PyObject
*self
, PyObject
*args
)
262 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
264 if (x
< 0 || x
>= 256) {
265 PyErr_SetString(PyExc_ValueError
,
266 "chr() arg not in range(256)");
270 return PyString_FromStringAndSize(s
, 1);
273 static char chr_doc
[] =
274 "chr(i) -> character\n\
276 Return a string of one character with ordinal i; 0 <= i < 256.";
279 #ifdef Py_USING_UNICODE
281 builtin_unichr(PyObject
*self
, PyObject
*args
)
286 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
289 #ifdef Py_UNICODE_WIDE
290 if (x
< 0 || x
> 0x10ffff) {
291 PyErr_SetString(PyExc_ValueError
,
292 "unichr() arg not in range(0x110000) "
293 "(wide Python build)");
297 if (x
< 0 || x
> 0xffff) {
298 PyErr_SetString(PyExc_ValueError
,
299 "unichr() arg not in range(0x10000) "
300 "(narrow Python build)");
306 /* UCS-2 character */
307 s
[0] = (Py_UNICODE
) x
;
308 return PyUnicode_FromUnicode(s
, 1);
311 #ifndef Py_UNICODE_WIDE
312 /* UCS-4 character. store as two surrogate characters */
314 s
[0] = 0xD800 + (Py_UNICODE
) (x
>> 10);
315 s
[1] = 0xDC00 + (Py_UNICODE
) (x
& 0x03FF);
316 return PyUnicode_FromUnicode(s
, 2);
318 s
[0] = (Py_UNICODE
)x
;
319 return PyUnicode_FromUnicode(s
, 1);
324 static char unichr_doc
[] =
325 "unichr(i) -> Unicode character\n\
327 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.";
332 builtin_cmp(PyObject
*self
, PyObject
*args
)
337 if (!PyArg_ParseTuple(args
, "OO:cmp", &a
, &b
))
339 if (PyObject_Cmp(a
, b
, &c
) < 0)
341 return PyInt_FromLong((long)c
);
344 static char cmp_doc
[] =
345 "cmp(x, y) -> integer\n\
347 Return negative if x<y, zero if x==y, positive if x>y.";
351 builtin_coerce(PyObject
*self
, PyObject
*args
)
356 if (!PyArg_ParseTuple(args
, "OO:coerce", &v
, &w
))
358 if (PyNumber_Coerce(&v
, &w
) < 0)
360 res
= Py_BuildValue("(OO)", v
, w
);
366 static char coerce_doc
[] =
367 "coerce(x, y) -> None or (x1, y1)\n\
369 When x and y can be coerced to values of the same type, return a tuple\n\
370 containing the coerced values. When they can't be coerced, return None.";
374 builtin_compile(PyObject
*self
, PyObject
*args
)
380 int dont_inherit
= 0;
381 int supplied_flags
= 0;
384 if (!PyArg_ParseTuple(args
, "sss|ii:compile", &str
, &filename
,
385 &startstr
, &supplied_flags
, &dont_inherit
))
388 if (strcmp(startstr
, "exec") == 0)
389 start
= Py_file_input
;
390 else if (strcmp(startstr
, "eval") == 0)
391 start
= Py_eval_input
;
392 else if (strcmp(startstr
, "single") == 0)
393 start
= Py_single_input
;
395 PyErr_SetString(PyExc_ValueError
,
396 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
400 if (supplied_flags
& ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
)) {
401 PyErr_SetString(PyExc_ValueError
,
402 "compile(): unrecognised flags");
405 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
407 cf
.cf_flags
= supplied_flags
;
409 PyEval_MergeCompilerFlags(&cf
);
411 return Py_CompileStringFlags(str
, filename
, start
, &cf
);
414 static char compile_doc
[] =
415 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
417 Compile the source string (a Python module, statement or expression)\n\
418 into a code object that can be executed by the exec statement or eval().\n\
419 The filename will be used for run-time error messages.\n\
420 The mode must be 'exec' to compile a module, 'single' to compile a\n\
421 single (interactive) statement, or 'eval' to compile an expression.\n\
422 The flags argument, if present, controls which future statements influence\n\
423 the compilation of the code.\n\
424 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
425 the effects of any future statements in effect in the code calling\n\
426 compile; if absent or zero these statements do influence the compilation,\n\
427 in addition to any features explicitly specified.";
431 builtin_dir(PyObject
*self
, PyObject
*args
)
433 static char *attrlist
[] = {"__members__", "__methods__", NULL
};
434 PyObject
*v
= NULL
, *l
= NULL
, *m
= NULL
;
439 if (!PyArg_ParseTuple(args
, "|O:dir", &v
))
442 x
= PyEval_GetLocals();
445 l
= PyMapping_Keys(x
);
450 d
= PyObject_GetAttrString(v
, "__dict__");
454 l
= PyMapping_Keys(d
);
464 for (s
= attrlist
; *s
!= NULL
; s
++) {
465 m
= PyObject_GetAttrString(v
, *s
);
471 x
= PySequence_GetItem(m
, i
);
476 if (PyList_Append(l
, x
) != 0) {
486 if (PyList_Sort(l
) != 0)
494 static char dir_doc
[] =
495 "dir([object]) -> list of strings\n\
497 Return an alphabetized list of names comprising (some of) the attributes\n\
498 of the given object. Without an argument, the names in the current scope\n\
499 are listed. With an instance argument, only the instance attributes are\n\
500 returned. With a class argument, attributes of the base class are not\n\
501 returned. For other types or arguments, this may list members or methods.";
505 builtin_divmod(PyObject
*self
, PyObject
*args
)
509 if (!PyArg_ParseTuple(args
, "OO:divmod", &v
, &w
))
511 return PyNumber_Divmod(v
, w
);
514 static char divmod_doc
[] =
515 "divmod(x, y) -> (div, mod)\n\
517 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
521 builtin_eval(PyObject
*self
, PyObject
*args
)
524 PyObject
*globals
= Py_None
, *locals
= Py_None
;
528 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
530 &PyDict_Type
, &globals
,
531 &PyDict_Type
, &locals
))
533 if (globals
== Py_None
) {
534 globals
= PyEval_GetGlobals();
535 if (locals
== Py_None
)
536 locals
= PyEval_GetLocals();
538 else if (locals
== Py_None
)
541 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
542 if (PyDict_SetItemString(globals
, "__builtins__",
543 PyEval_GetBuiltins()) != 0)
547 if (PyCode_Check(cmd
)) {
548 if (PyTuple_GET_SIZE(((PyCodeObject
*)cmd
)->co_freevars
) > 0) {
549 PyErr_SetString(PyExc_TypeError
,
550 "code object passed to eval() may not contain free variables");
553 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
556 if (!PyString_Check(cmd
) &&
557 !PyUnicode_Check(cmd
)) {
558 PyErr_SetString(PyExc_TypeError
,
559 "eval() arg 1 must be a string or code object");
562 if (PyString_AsStringAndSize(cmd
, &str
, NULL
))
564 while (*str
== ' ' || *str
== '\t')
568 (void)PyEval_MergeCompilerFlags(&cf
);
569 return PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
572 static char eval_doc
[] =
573 "eval(source[, globals[, locals]]) -> value\n\
575 Evaluate the source in the context of globals and locals.\n\
576 The source may be a string representing a Python expression\n\
577 or a code object as returned by compile().\n\
578 The globals and locals are dictionaries, defaulting to the current\n\
579 globals and locals. If only globals is given, locals defaults to it.";
583 builtin_execfile(PyObject
*self
, PyObject
*args
)
586 PyObject
*globals
= Py_None
, *locals
= Py_None
;
593 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
595 &PyDict_Type
, &globals
,
596 &PyDict_Type
, &locals
))
598 if (globals
== Py_None
) {
599 globals
= PyEval_GetGlobals();
600 if (locals
== Py_None
)
601 locals
= PyEval_GetLocals();
603 else if (locals
== Py_None
)
605 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
606 if (PyDict_SetItemString(globals
, "__builtins__",
607 PyEval_GetBuiltins()) != 0)
612 /* Test for existence or directory. */
613 if (!stat(filename
, &s
)) {
614 if (S_ISDIR(s
.st_mode
))
621 Py_BEGIN_ALLOW_THREADS
622 fp
= fopen(filename
, "r");
631 PyErr_SetFromErrno(PyExc_IOError
);
635 if (PyEval_MergeCompilerFlags(&cf
))
636 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
639 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
644 static char execfile_doc
[] =
645 "execfile(filename[, globals[, locals]])\n\
647 Read and execute a Python script from a file.\n\
648 The globals and locals are dictionaries, defaulting to the current\n\
649 globals and locals. If only globals is given, locals defaults to it.";
653 builtin_getattr(PyObject
*self
, PyObject
*args
)
655 PyObject
*v
, *result
, *dflt
= NULL
;
658 if (!PyArg_ParseTuple(args
, "OO|O:getattr", &v
, &name
, &dflt
))
660 #ifdef Py_USING_UNICODE
661 if (PyUnicode_Check(name
)) {
662 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
668 if (!PyString_Check(name
)) {
669 PyErr_SetString(PyExc_TypeError
,
670 "attribute name must be string");
673 result
= PyObject_GetAttr(v
, name
);
674 if (result
== NULL
&& dflt
!= NULL
) {
682 static char getattr_doc
[] =
683 "getattr(object, name[, default]) -> value\n\
685 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
686 When a default argument is given, it is returned when the attribute doesn't\n\
687 exist; without it, an exception is raised in that case.";
691 builtin_globals(PyObject
*self
)
695 d
= PyEval_GetGlobals();
700 static char globals_doc
[] =
701 "globals() -> dictionary\n\
703 Return the dictionary containing the current scope's global variables.";
707 builtin_hasattr(PyObject
*self
, PyObject
*args
)
712 if (!PyArg_ParseTuple(args
, "OO:hasattr", &v
, &name
))
714 #ifdef Py_USING_UNICODE
715 if (PyUnicode_Check(name
)) {
716 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
722 if (!PyString_Check(name
)) {
723 PyErr_SetString(PyExc_TypeError
,
724 "attribute name must be string");
727 v
= PyObject_GetAttr(v
, name
);
738 static char hasattr_doc
[] =
739 "hasattr(object, name) -> Boolean\n\
741 Return whether the object has an attribute with the given name.\n\
742 (This is done by calling getattr(object, name) and catching exceptions.)";
746 builtin_id(PyObject
*self
, PyObject
*v
)
748 return PyLong_FromVoidPtr(v
);
751 static char id_doc
[] =
752 "id(object) -> integer\n\
754 Return the identity of an object. This is guaranteed to be unique among\n\
755 simultaneously existing objects. (Hint: it's the object's memory address.)";
759 builtin_map(PyObject
*self
, PyObject
*args
)
762 PyObject
*it
; /* the iterator object */
763 int saw_StopIteration
; /* bool: did the iterator end? */
766 PyObject
*func
, *result
;
767 sequence
*seqs
= NULL
, *sqp
;
771 n
= PyTuple_Size(args
);
773 PyErr_SetString(PyExc_TypeError
,
774 "map() requires at least two args");
778 func
= PyTuple_GetItem(args
, 0);
781 if (func
== Py_None
&& n
== 1) {
782 /* map(None, S) is the same as list(S). */
783 return PySequence_List(PyTuple_GetItem(args
, 1));
786 /* Get space for sequence descriptors. Must NULL out the iterator
787 * pointers so that jumping to Fail_2 later doesn't see trash.
789 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
793 for (i
= 0; i
< n
; ++i
) {
794 seqs
[i
].it
= (PyObject
*)NULL
;
795 seqs
[i
].saw_StopIteration
= 0;
798 /* Do a first pass to obtain iterators for the arguments, and set len
799 * to the largest of their lengths.
802 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
807 curseq
= PyTuple_GetItem(args
, i
+1);
808 sqp
->it
= PyObject_GetIter(curseq
);
809 if (sqp
->it
== NULL
) {
810 static char errmsg
[] =
811 "argument %d to map() must support iteration";
812 char errbuf
[sizeof(errmsg
) + 25];
813 sprintf(errbuf
, errmsg
, i
+2);
814 PyErr_SetString(PyExc_TypeError
, errbuf
);
819 curlen
= -1; /* unknown */
820 if (PySequence_Check(curseq
) &&
821 curseq
->ob_type
->tp_as_sequence
->sq_length
) {
822 curlen
= PySequence_Size(curseq
);
827 curlen
= 8; /* arbitrary */
832 /* Get space for the result list. */
833 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
836 /* Iterate over the sequences until all have stopped. */
838 PyObject
*alist
, *item
=NULL
, *value
;
841 if (func
== Py_None
&& n
== 1)
843 else if ((alist
= PyTuple_New(n
)) == NULL
)
846 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
847 if (sqp
->saw_StopIteration
) {
852 item
= PyIter_Next(sqp
->it
);
856 if (PyErr_Occurred()) {
862 sqp
->saw_StopIteration
= 1;
866 PyTuple_SET_ITEM(alist
, j
, item
);
874 if (numactive
== 0) {
882 value
= PyEval_CallObject(func
, alist
);
888 int status
= PyList_Append(result
, value
);
893 else if (PyList_SetItem(result
, i
, value
) < 0)
897 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
908 for (i
= 0; i
< n
; ++i
)
909 Py_XDECREF(seqs
[i
].it
);
914 static char map_doc
[] =
915 "map(function, sequence[, sequence, ...]) -> list\n\
917 Return a list of the results of applying the function to the items of\n\
918 the argument sequence(s). If more than one sequence is given, the\n\
919 function is called with an argument list consisting of the corresponding\n\
920 item of each sequence, substituting None for missing values when not all\n\
921 sequences have the same length. If the function is None, return a list of\n\
922 the items of the sequence (or a list of tuples if more than one sequence).";
926 builtin_setattr(PyObject
*self
, PyObject
*args
)
932 if (!PyArg_ParseTuple(args
, "OOO:setattr", &v
, &name
, &value
))
934 if (PyObject_SetAttr(v
, name
, value
) != 0)
940 static char setattr_doc
[] =
941 "setattr(object, name, value)\n\
943 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
948 builtin_delattr(PyObject
*self
, PyObject
*args
)
953 if (!PyArg_ParseTuple(args
, "OO:delattr", &v
, &name
))
955 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
961 static char delattr_doc
[] =
962 "delattr(object, name)\n\
964 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
969 builtin_hash(PyObject
*self
, PyObject
*v
)
973 x
= PyObject_Hash(v
);
976 return PyInt_FromLong(x
);
979 static char hash_doc
[] =
980 "hash(object) -> integer\n\
982 Return a hash value for the object. Two objects with the same value have\n\
983 the same hash value. The reverse is not necessarily true, but likely.";
987 builtin_hex(PyObject
*self
, PyObject
*v
)
991 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
992 nb
->nb_hex
== NULL
) {
993 PyErr_SetString(PyExc_TypeError
,
994 "hex() argument can't be converted to hex");
997 return (*nb
->nb_hex
)(v
);
1000 static char hex_doc
[] =
1001 "hex(number) -> string\n\
1003 Return the hexadecimal representation of an integer or long integer.";
1006 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1009 builtin_input(PyObject
*self
, PyObject
*args
)
1014 PyObject
*globals
, *locals
;
1016 line
= builtin_raw_input(self
, args
);
1019 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1021 while (*str
== ' ' || *str
== '\t')
1023 globals
= PyEval_GetGlobals();
1024 locals
= PyEval_GetLocals();
1025 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1026 if (PyDict_SetItemString(globals
, "__builtins__",
1027 PyEval_GetBuiltins()) != 0)
1030 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
1035 static char input_doc
[] =
1036 "input([prompt]) -> value\n\
1038 Equivalent to eval(raw_input(prompt)).";
1042 builtin_intern(PyObject
*self
, PyObject
*args
)
1045 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1048 PyString_InternInPlace(&s
);
1052 static char intern_doc
[] =
1053 "intern(string) -> string\n\
1055 ``Intern'' the given string. This enters the string in the (global)\n\
1056 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1057 Return the string itself or the previously interned string object with the\n\
1062 builtin_iter(PyObject
*self
, PyObject
*args
)
1064 PyObject
*v
, *w
= NULL
;
1066 if (!PyArg_ParseTuple(args
, "O|O:iter", &v
, &w
))
1069 return PyObject_GetIter(v
);
1070 if (!PyCallable_Check(v
)) {
1071 PyErr_SetString(PyExc_TypeError
,
1072 "iter(v, w): v must be callable");
1075 return PyCallIter_New(v
, w
);
1078 static char iter_doc
[] =
1079 "iter(collection) -> iterator\n\
1080 iter(callable, sentinel) -> iterator\n\
1082 Get an iterator from an object. In the first form, the argument must\n\
1083 supply its own iterator, or be a sequence.\n\
1084 In the second form, the callable is called until it returns the sentinel.";
1088 builtin_len(PyObject
*self
, PyObject
*v
)
1092 res
= PyObject_Size(v
);
1093 if (res
< 0 && PyErr_Occurred())
1095 return PyInt_FromLong(res
);
1098 static char len_doc
[] =
1099 "len(object) -> integer\n\
1101 Return the number of items of a sequence or mapping.";
1105 builtin_slice(PyObject
*self
, PyObject
*args
)
1107 PyObject
*start
, *stop
, *step
;
1109 start
= stop
= step
= NULL
;
1111 if (!PyArg_ParseTuple(args
, "O|OO:slice", &start
, &stop
, &step
))
1114 /* This swapping of stop and start is to maintain similarity with
1120 return PySlice_New(start
, stop
, step
);
1123 static char slice_doc
[] =
1124 "slice([start,] stop[, step]) -> slice object\n\
1126 Create a slice object. This is used for slicing by the Numeric extensions.";
1130 builtin_locals(PyObject
*self
)
1134 d
= PyEval_GetLocals();
1139 static char locals_doc
[] =
1140 "locals() -> dictionary\n\
1142 Return the dictionary containing the current scope's local variables.";
1146 min_max(PyObject
*args
, int op
)
1148 PyObject
*v
, *w
, *x
, *it
;
1150 if (PyTuple_Size(args
) > 1)
1152 else if (!PyArg_ParseTuple(args
, "O:min/max", &v
))
1155 it
= PyObject_GetIter(v
);
1159 w
= NULL
; /* the result */
1161 x
= PyIter_Next(it
);
1163 if (PyErr_Occurred()) {
1174 int cmp
= PyObject_RichCompareBool(x
, w
, op
);
1190 PyErr_SetString(PyExc_ValueError
,
1191 "min() or max() arg is an empty sequence");
1197 builtin_min(PyObject
*self
, PyObject
*v
)
1199 return min_max(v
, Py_LT
);
1202 static char min_doc
[] =
1203 "min(sequence) -> value\n\
1204 min(a, b, c, ...) -> value\n\
1206 With a single sequence argument, return its smallest item.\n\
1207 With two or more arguments, return the smallest argument.";
1211 builtin_max(PyObject
*self
, PyObject
*v
)
1213 return min_max(v
, Py_GT
);
1216 static char max_doc
[] =
1217 "max(sequence) -> value\n\
1218 max(a, b, c, ...) -> value\n\
1220 With a single sequence argument, return its largest item.\n\
1221 With two or more arguments, return the largest argument.";
1225 builtin_oct(PyObject
*self
, PyObject
*v
)
1227 PyNumberMethods
*nb
;
1229 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1230 nb
->nb_oct
== NULL
) {
1231 PyErr_SetString(PyExc_TypeError
,
1232 "oct() argument can't be converted to oct");
1235 return (*nb
->nb_oct
)(v
);
1238 static char oct_doc
[] =
1239 "oct(number) -> string\n\
1241 Return the octal representation of an integer or long integer.";
1245 builtin_open(PyObject
*self
, PyObject
*args
)
1252 if (!PyArg_ParseTuple(args
, "et|si:open", Py_FileSystemDefaultEncoding
,
1253 &name
, &mode
, &bufsize
))
1255 f
= PyFile_FromString(name
, mode
);
1256 PyMem_Free(name
); /* free the encoded string */
1258 PyFile_SetBufSize(f
, bufsize
);
1262 static char open_doc
[] =
1263 "open(filename[, mode[, buffering]]) -> file object\n\
1265 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1266 writing or appending. The file will be created if it doesn't exist\n\
1267 when opened for writing or appending; it will be truncated when\n\
1268 opened for writing. Add a 'b' to the mode for binary files.\n\
1269 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1270 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1271 buffered, and larger numbers specify the buffer size.";
1275 builtin_ord(PyObject
*self
, PyObject
* obj
)
1280 if (PyString_Check(obj
)) {
1281 size
= PyString_GET_SIZE(obj
);
1283 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1284 return PyInt_FromLong(ord
);
1286 #ifdef Py_USING_UNICODE
1287 } else if (PyUnicode_Check(obj
)) {
1288 size
= PyUnicode_GET_SIZE(obj
);
1290 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1291 return PyInt_FromLong(ord
);
1295 PyErr_Format(PyExc_TypeError
,
1296 "ord() expected string of length 1, but " \
1297 "%.200s found", obj
->ob_type
->tp_name
);
1301 PyErr_Format(PyExc_TypeError
,
1302 "ord() expected a character, "
1303 "but string of length %d found",
1308 static char ord_doc
[] =
1309 "ord(c) -> integer\n\
1311 Return the integer ordinal of a one-character string.";
1315 builtin_pow(PyObject
*self
, PyObject
*args
)
1317 PyObject
*v
, *w
, *z
= Py_None
;
1319 if (!PyArg_ParseTuple(args
, "OO|O:pow", &v
, &w
, &z
))
1321 return PyNumber_Power(v
, w
, z
);
1324 static char pow_doc
[] =
1325 "pow(x, y[, z]) -> number\n\
1327 With two arguments, equivalent to x**y. With three arguments,\n\
1328 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1331 /* Return number of items in range/xrange (lo, hi, step). step > 0
1332 * required. Return a value < 0 if & only if the true value is too
1333 * large to fit in a signed long.
1336 get_len_of_range(long lo
, long hi
, long step
)
1338 /* -------------------------------------------------------------
1339 If lo >= hi, the range is empty.
1340 Else if n values are in the range, the last one is
1341 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1342 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1343 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1344 the RHS is non-negative and so truncation is the same as the
1345 floor. Letting M be the largest positive long, the worst case
1346 for the RHS numerator is hi=M, lo=-M-1, and then
1347 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1348 precision to compute the RHS exactly.
1349 ---------------------------------------------------------------*/
1352 unsigned long uhi
= (unsigned long)hi
;
1353 unsigned long ulo
= (unsigned long)lo
;
1354 unsigned long diff
= uhi
- ulo
- 1;
1355 n
= (long)(diff
/ (unsigned long)step
+ 1);
1361 builtin_range(PyObject
*self
, PyObject
*args
)
1363 long ilow
= 0, ihigh
= 0, istep
= 1;
1369 if (PyTuple_Size(args
) <= 1) {
1370 if (!PyArg_ParseTuple(args
,
1371 "l;range() requires 1-3 int arguments",
1376 if (!PyArg_ParseTuple(args
,
1377 "ll|l;range() requires 1-3 int arguments",
1378 &ilow
, &ihigh
, &istep
))
1382 PyErr_SetString(PyExc_ValueError
, "range() arg 3 must not be zero");
1386 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1388 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1390 if (bign
< 0 || (long)n
!= bign
) {
1391 PyErr_SetString(PyExc_OverflowError
,
1392 "range() result has too many items");
1398 for (i
= 0; i
< n
; i
++) {
1399 PyObject
*w
= PyInt_FromLong(ilow
);
1404 PyList_SET_ITEM(v
, i
, w
);
1410 static char range_doc
[] =
1411 "range([start,] stop[, step]) -> list of integers\n\
1413 Return a list containing an arithmetic progression of integers.\n\
1414 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1415 When step is given, it specifies the increment (or decrement).\n\
1416 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1417 These are exactly the valid indices for a list of 4 elements.";
1421 builtin_xrange(PyObject
*self
, PyObject
*args
)
1423 long ilow
= 0, ihigh
= 0, istep
= 1;
1426 if (PyTuple_Size(args
) <= 1) {
1427 if (!PyArg_ParseTuple(args
,
1428 "l;xrange() requires 1-3 int arguments",
1433 if (!PyArg_ParseTuple(args
,
1434 "ll|l;xrange() requires 1-3 int arguments",
1435 &ilow
, &ihigh
, &istep
))
1439 PyErr_SetString(PyExc_ValueError
, "xrange() arg 3 must not be zero");
1443 n
= get_len_of_range(ilow
, ihigh
, istep
);
1445 n
= get_len_of_range(ihigh
, ilow
, -istep
);
1447 PyErr_SetString(PyExc_OverflowError
,
1448 "xrange() result has too many items");
1451 return PyRange_New(ilow
, n
, istep
, 1);
1454 static char xrange_doc
[] =
1455 "xrange([start,] stop[, step]) -> xrange object\n\
1457 Like range(), but instead of returning a list, returns an object that\n\
1458 generates the numbers in the range on demand. This is slightly slower\n\
1459 than range() but more memory efficient.";
1463 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1468 if (!PyArg_ParseTuple(args
, "|O:[raw_]input", &v
))
1470 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin
&&
1471 PyFile_AsFile(PySys_GetObject("stdout")) == stdout
&&
1472 isatty(fileno(stdin
)) && isatty(fileno(stdout
))) {
1478 po
= PyObject_Str(v
);
1481 prompt
= PyString_AsString(po
);
1489 s
= PyOS_Readline(prompt
);
1492 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1496 PyErr_SetNone(PyExc_EOFError
);
1499 else { /* strip trailing '\n' */
1500 size_t len
= strlen(s
);
1501 if (len
> INT_MAX
) {
1502 PyErr_SetString(PyExc_OverflowError
, "input too long");
1506 result
= PyString_FromStringAndSize(s
, (int)(len
-1));
1513 f
= PySys_GetObject("stdout");
1515 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
1518 if (Py_FlushLine() != 0 ||
1519 PyFile_WriteObject(v
, f
, Py_PRINT_RAW
) != 0)
1522 f
= PySys_GetObject("stdin");
1524 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdin");
1527 return PyFile_GetLine(f
, -1);
1530 static char raw_input_doc
[] =
1531 "raw_input([prompt]) -> string\n\
1533 Read a string from standard input. The trailing newline is stripped.\n\
1534 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1535 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1536 is printed without a trailing newline before reading.";
1540 builtin_reduce(PyObject
*self
, PyObject
*args
)
1542 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1544 if (!PyArg_ParseTuple(args
, "OO|O:reduce", &func
, &seq
, &result
))
1549 it
= PyObject_GetIter(seq
);
1551 PyErr_SetString(PyExc_TypeError
,
1552 "reduce() arg 2 must support iteration");
1557 if ((args
= PyTuple_New(2)) == NULL
)
1563 if (args
->ob_refcnt
> 1) {
1565 if ((args
= PyTuple_New(2)) == NULL
)
1569 op2
= PyIter_Next(it
);
1571 if (PyErr_Occurred())
1579 PyTuple_SetItem(args
, 0, result
);
1580 PyTuple_SetItem(args
, 1, op2
);
1581 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1589 PyErr_SetString(PyExc_TypeError
,
1590 "reduce() of empty sequence with no initial value");
1602 static char reduce_doc
[] =
1603 "reduce(function, sequence[, initial]) -> value\n\
1605 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1606 from left to right, so as to reduce the sequence to a single value.\n\
1607 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1608 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1609 of the sequence in the calculation, and serves as a default when the\n\
1610 sequence is empty.";
1614 builtin_reload(PyObject
*self
, PyObject
*v
)
1616 return PyImport_ReloadModule(v
);
1619 static char reload_doc
[] =
1620 "reload(module) -> module\n\
1622 Reload the module. The module must have been successfully imported before.";
1626 builtin_repr(PyObject
*self
, PyObject
*v
)
1628 return PyObject_Repr(v
);
1631 static char repr_doc
[] =
1632 "repr(object) -> string\n\
1634 Return the canonical string representation of the object.\n\
1635 For most object types, eval(repr(object)) == object.";
1639 builtin_round(PyObject
*self
, PyObject
*args
)
1646 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1664 return PyFloat_FromDouble(x
);
1667 static char round_doc
[] =
1668 "round(number[, ndigits]) -> floating point number\n\
1670 Round a number to a given precision in decimal digits (default 0 digits).\n\
1671 This always returns a floating point number. Precision may be negative.";
1675 builtin_vars(PyObject
*self
, PyObject
*args
)
1680 if (!PyArg_ParseTuple(args
, "|O:vars", &v
))
1683 d
= PyEval_GetLocals();
1685 if (!PyErr_Occurred())
1686 PyErr_SetString(PyExc_SystemError
,
1693 d
= PyObject_GetAttrString(v
, "__dict__");
1695 PyErr_SetString(PyExc_TypeError
,
1696 "vars() argument must have __dict__ attribute");
1703 static char vars_doc
[] =
1704 "vars([object]) -> dictionary\n\
1706 Without arguments, equivalent to locals().\n\
1707 With an argument, equivalent to object.__dict__.";
1710 builtin_isinstance(PyObject
*self
, PyObject
*args
)
1716 if (!PyArg_ParseTuple(args
, "OO:isinstance", &inst
, &cls
))
1719 retval
= PyObject_IsInstance(inst
, cls
);
1722 return PyInt_FromLong(retval
);
1725 static char isinstance_doc
[] =
1726 "isinstance(object, class-or-type) -> Boolean\n\
1728 Return whether an object is an instance of a class or of a subclass thereof.\n\
1729 With a type as second argument, return whether that is the object's type.";
1733 builtin_issubclass(PyObject
*self
, PyObject
*args
)
1739 if (!PyArg_ParseTuple(args
, "OO:issubclass", &derived
, &cls
))
1742 retval
= PyObject_IsSubclass(derived
, cls
);
1745 return PyInt_FromLong(retval
);
1748 static char issubclass_doc
[] =
1749 "issubclass(C, B) -> Boolean\n\
1751 Return whether class C is a subclass (i.e., a derived class) of class B.";
1755 builtin_zip(PyObject
*self
, PyObject
*args
)
1758 int itemsize
= PySequence_Length(args
);
1760 PyObject
*itlist
; /* tuple of iterators */
1763 PyErr_SetString(PyExc_TypeError
,
1764 "zip() requires at least one sequence");
1767 /* args must be a tuple */
1768 assert(PyTuple_Check(args
));
1770 /* allocate result list */
1771 if ((ret
= PyList_New(0)) == NULL
)
1774 /* obtain iterators */
1775 itlist
= PyTuple_New(itemsize
);
1778 for (i
= 0; i
< itemsize
; ++i
) {
1779 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
1780 PyObject
*it
= PyObject_GetIter(item
);
1782 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1783 PyErr_Format(PyExc_TypeError
,
1784 "zip argument #%d must support iteration",
1786 goto Fail_ret_itlist
;
1788 PyTuple_SET_ITEM(itlist
, i
, it
);
1791 /* build result into ret list */
1794 PyObject
*next
= PyTuple_New(itemsize
);
1796 goto Fail_ret_itlist
;
1798 for (i
= 0; i
< itemsize
; i
++) {
1799 PyObject
*it
= PyTuple_GET_ITEM(itlist
, i
);
1800 PyObject
*item
= PyIter_Next(it
);
1802 if (PyErr_Occurred()) {
1810 PyTuple_SET_ITEM(next
, i
, item
);
1813 status
= PyList_Append(ret
, next
);
1816 goto Fail_ret_itlist
;
1827 static char zip_doc
[] =
1828 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1830 Return a list of tuples, where each tuple contains the i-th element\n\
1831 from each of the argument sequences. The returned list is truncated\n\
1832 in length to the length of the shortest argument sequence.";
1835 static PyMethodDef builtin_methods
[] = {
1836 {"__import__", builtin___import__
, METH_VARARGS
, import_doc
},
1837 {"abs", builtin_abs
, METH_O
, abs_doc
},
1838 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
1839 {"buffer", builtin_buffer
, METH_VARARGS
, buffer_doc
},
1840 {"callable", builtin_callable
, METH_O
, callable_doc
},
1841 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
1842 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
1843 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
1844 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
1845 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
1846 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
1847 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
1848 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
1849 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
1850 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
1851 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
1852 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
1853 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
1854 {"hash", builtin_hash
, METH_O
, hash_doc
},
1855 {"hex", builtin_hex
, METH_O
, hex_doc
},
1856 {"id", builtin_id
, METH_O
, id_doc
},
1857 {"input", builtin_input
, METH_VARARGS
, input_doc
},
1858 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
1859 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
1860 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
1861 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
1862 {"len", builtin_len
, METH_O
, len_doc
},
1863 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
1864 {"map", builtin_map
, METH_VARARGS
, map_doc
},
1865 {"max", builtin_max
, METH_VARARGS
, max_doc
},
1866 {"min", builtin_min
, METH_VARARGS
, min_doc
},
1867 {"oct", builtin_oct
, METH_O
, oct_doc
},
1868 {"open", builtin_open
, METH_VARARGS
, open_doc
},
1869 {"ord", builtin_ord
, METH_O
, ord_doc
},
1870 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
1871 {"range", builtin_range
, METH_VARARGS
, range_doc
},
1872 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
1873 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
1874 {"reload", builtin_reload
, METH_O
, reload_doc
},
1875 {"repr", builtin_repr
, METH_O
, repr_doc
},
1876 {"round", builtin_round
, METH_VARARGS
, round_doc
},
1877 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
1878 {"slice", builtin_slice
, METH_VARARGS
, slice_doc
},
1879 #ifdef Py_USING_UNICODE
1880 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
1882 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
1883 {"xrange", builtin_xrange
, METH_VARARGS
, xrange_doc
},
1884 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
1888 static char builtin_doc
[] =
1889 "Built-in functions, exceptions, and other objects.\n\
1891 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
1894 _PyBuiltin_Init(void)
1896 PyObject
*mod
, *dict
, *debug
;
1897 mod
= Py_InitModule4("__builtin__", builtin_methods
,
1898 builtin_doc
, (PyObject
*)NULL
,
1899 PYTHON_API_VERSION
);
1902 dict
= PyModule_GetDict(mod
);
1903 if (PyDict_SetItemString(dict
, "None", Py_None
) < 0)
1905 if (PyDict_SetItemString(dict
, "Ellipsis", Py_Ellipsis
) < 0)
1907 if (PyDict_SetItemString(dict
, "NotImplemented",
1908 Py_NotImplemented
) < 0)
1910 if (PyDict_SetItemString(dict
, "classmethod",
1911 (PyObject
*) &PyClassMethod_Type
) < 0)
1913 #ifndef WITHOUT_COMPLEX
1914 if (PyDict_SetItemString(dict
, "complex",
1915 (PyObject
*) &PyComplex_Type
) < 0)
1918 if (PyDict_SetItemString(dict
, "dictionary",
1919 (PyObject
*) &PyDict_Type
) < 0)
1921 if (PyDict_SetItemString(dict
, "float",
1922 (PyObject
*) &PyFloat_Type
) < 0)
1924 if (PyDict_SetItemString(dict
, "int", (PyObject
*) &PyInt_Type
) < 0)
1926 if (PyDict_SetItemString(dict
, "list", (PyObject
*) &PyList_Type
) < 0)
1928 if (PyDict_SetItemString(dict
, "long", (PyObject
*) &PyLong_Type
) < 0)
1930 if (PyDict_SetItemString(dict
, "object",
1931 (PyObject
*) &PyBaseObject_Type
) < 0)
1933 if (PyDict_SetItemString(dict
, "staticmethod",
1934 (PyObject
*) &PyStaticMethod_Type
) < 0)
1936 if (PyDict_SetItemString(dict
, "str", (PyObject
*) &PyString_Type
) < 0)
1938 if (PyDict_SetItemString(dict
, "tuple",
1939 (PyObject
*) &PyTuple_Type
) < 0)
1941 if (PyDict_SetItemString(dict
, "type", (PyObject
*) &PyType_Type
) < 0)
1943 #ifdef Py_USING_UNICODE
1944 if (PyDict_SetItemString(dict
, "unicode",
1945 (PyObject
*) &PyUnicode_Type
) < 0)
1948 debug
= PyInt_FromLong(Py_OptimizeFlag
== 0);
1949 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
1958 /* Helper for filter(): filter a tuple through a function */
1961 filtertuple(PyObject
*func
, PyObject
*tuple
)
1965 int len
= PyTuple_Size(tuple
);
1972 if ((result
= PyTuple_New(len
)) == NULL
)
1975 for (i
= j
= 0; i
< len
; ++i
) {
1976 PyObject
*item
, *good
;
1979 if ((item
= PyTuple_GetItem(tuple
, i
)) == NULL
)
1981 if (func
== Py_None
) {
1986 PyObject
*arg
= Py_BuildValue("(O)", item
);
1989 good
= PyEval_CallObject(func
, arg
);
1994 ok
= PyObject_IsTrue(good
);
1998 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2003 if (_PyTuple_Resize(&result
, j
) < 0)
2014 /* Helper for filter(): filter a string through a function */
2017 filterstring(PyObject
*func
, PyObject
*strobj
)
2021 int len
= PyString_Size(strobj
);
2023 if (func
== Py_None
) {
2024 /* No character is ever false -- share input string */
2028 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2031 for (i
= j
= 0; i
< len
; ++i
) {
2032 PyObject
*item
, *arg
, *good
;
2035 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2038 arg
= Py_BuildValue("(O)", item
);
2043 good
= PyEval_CallObject(func
, arg
);
2049 ok
= PyObject_IsTrue(good
);
2052 PyString_AS_STRING((PyStringObject
*)result
)[j
++] =
2053 PyString_AS_STRING((PyStringObject
*)item
)[0];
2057 if (j
< len
&& _PyString_Resize(&result
, j
) < 0)