1 /* Built-in functions */
12 #include "unixstuff.h"
15 /* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
18 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
19 const char *Py_FileSystemDefaultEncoding
= "mbcs";
20 #elif defined(__APPLE__)
21 const char *Py_FileSystemDefaultEncoding
= "utf-8";
23 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
27 static PyObject
*filterstring(PyObject
*, PyObject
*);
28 #ifdef Py_USING_UNICODE
29 static PyObject
*filterunicode(PyObject
*, PyObject
*);
31 static PyObject
*filtertuple (PyObject
*, PyObject
*);
34 builtin___import__(PyObject
*self
, PyObject
*args
)
37 PyObject
*globals
= NULL
;
38 PyObject
*locals
= NULL
;
39 PyObject
*fromlist
= NULL
;
41 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
42 &name
, &globals
, &locals
, &fromlist
))
44 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
47 PyDoc_STRVAR(import_doc
,
48 "__import__(name, globals, locals, fromlist) -> module\n\
50 Import a module. The globals are only used to determine the context;\n\
51 they are not modified. The locals are currently unused. The fromlist\n\
52 should be a list of names to emulate ``from name import ...'', or an\n\
53 empty list to emulate ``import name''.\n\
54 When importing a module from a package, note that __import__('A.B', ...)\n\
55 returns package A when fromlist is empty, but its submodule B when\n\
56 fromlist is not empty.");
60 builtin_abs(PyObject
*self
, PyObject
*v
)
62 return PyNumber_Absolute(v
);
66 "abs(number) -> number\n\
68 Return the absolute value of the argument.");
71 builtin_all(PyObject
*self
, PyObject
*v
)
75 it
= PyObject_GetIter(v
);
79 while ((item
= PyIter_Next(it
)) != NULL
) {
80 int cmp
= PyObject_IsTrue(item
);
98 "all(iterable) -> bool\n\
100 Return True if bool(x) is True for all values x in the iterable.");
103 builtin_any(PyObject
*self
, PyObject
*v
)
107 it
= PyObject_GetIter(v
);
111 while ((item
= PyIter_Next(it
)) != NULL
) {
112 int cmp
= PyObject_IsTrue(item
);
124 if (PyErr_Occurred())
129 PyDoc_STRVAR(any_doc
,
130 "any(iterable) -> bool\n\
132 Return True if bool(x) is True for any x in the iterable.");
135 builtin_apply(PyObject
*self
, PyObject
*args
)
137 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
138 PyObject
*t
= NULL
, *retval
= NULL
;
140 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
143 if (!PyTuple_Check(alist
)) {
144 if (!PySequence_Check(alist
)) {
145 PyErr_Format(PyExc_TypeError
,
146 "apply() arg 2 expected sequence, found %s",
147 alist
->ob_type
->tp_name
);
150 t
= PySequence_Tuple(alist
);
156 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
157 PyErr_Format(PyExc_TypeError
,
158 "apply() arg 3 expected dictionary, found %s",
159 kwdict
->ob_type
->tp_name
);
162 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
168 PyDoc_STRVAR(apply_doc
,
169 "apply(object[, args[, kwargs]]) -> value\n\
171 Call a callable object with positional arguments taken from the tuple args,\n\
172 and keyword arguments taken from the optional dictionary kwargs.\n\
173 Note that classes are callable, as are instances with a __call__() method.\n\
175 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
176 function(*args, **keywords).");
180 builtin_callable(PyObject
*self
, PyObject
*v
)
182 return PyBool_FromLong((long)PyCallable_Check(v
));
185 PyDoc_STRVAR(callable_doc
,
186 "callable(object) -> bool\n\
188 Return whether the object is callable (i.e., some kind of function).\n\
189 Note that classes are callable, as are instances with a __call__() method.");
193 builtin_filter(PyObject
*self
, PyObject
*args
)
195 PyObject
*func
, *seq
, *result
, *it
, *arg
;
196 int len
; /* guess for result list size */
199 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
202 /* Strings and tuples return a result of the same type. */
203 if (PyString_Check(seq
))
204 return filterstring(func
, seq
);
205 #ifdef Py_USING_UNICODE
206 if (PyUnicode_Check(seq
))
207 return filterunicode(func
, seq
);
209 if (PyTuple_Check(seq
))
210 return filtertuple(func
, seq
);
212 /* Pre-allocate argument list tuple. */
213 arg
= PyTuple_New(1);
218 it
= PyObject_GetIter(seq
);
222 /* Guess a result list size. */
223 len
= _PyObject_LengthCue(seq
);
225 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
226 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
230 len
= 8; /* arbitrary */
233 /* Get a result list. */
234 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
235 /* Eww - can modify the list in-place. */
240 result
= PyList_New(len
);
245 /* Build the result list. */
251 item
= PyIter_Next(it
);
253 if (PyErr_Occurred())
258 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
259 ok
= PyObject_IsTrue(item
);
263 PyTuple_SET_ITEM(arg
, 0, item
);
264 good
= PyObject_Call(func
, arg
, NULL
);
265 PyTuple_SET_ITEM(arg
, 0, NULL
);
270 ok
= PyObject_IsTrue(good
);
275 PyList_SET_ITEM(result
, j
, item
);
277 int status
= PyList_Append(result
, item
);
289 /* Cut back result list if len is too big. */
290 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
306 PyDoc_STRVAR(filter_doc
,
307 "filter(function or None, sequence) -> list, tuple, or string\n"
309 "Return those items of sequence for which function(item) is true. If\n"
310 "function is None, return the items that are true. If sequence is a tuple\n"
311 "or string, return the same type, else return a list.");
314 builtin_chr(PyObject
*self
, PyObject
*args
)
319 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
321 if (x
< 0 || x
>= 256) {
322 PyErr_SetString(PyExc_ValueError
,
323 "chr() arg not in range(256)");
327 return PyString_FromStringAndSize(s
, 1);
330 PyDoc_STRVAR(chr_doc
,
331 "chr(i) -> character\n\
333 Return a string of one character with ordinal i; 0 <= i < 256.");
336 #ifdef Py_USING_UNICODE
338 builtin_unichr(PyObject
*self
, PyObject
*args
)
342 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
345 return PyUnicode_FromOrdinal(x
);
348 PyDoc_STRVAR(unichr_doc
,
349 "unichr(i) -> Unicode character\n\
351 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
356 builtin_cmp(PyObject
*self
, PyObject
*args
)
361 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
363 if (PyObject_Cmp(a
, b
, &c
) < 0)
365 return PyInt_FromLong((long)c
);
368 PyDoc_STRVAR(cmp_doc
,
369 "cmp(x, y) -> integer\n\
371 Return negative if x<y, zero if x==y, positive if x>y.");
375 builtin_coerce(PyObject
*self
, PyObject
*args
)
380 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
382 if (PyNumber_Coerce(&v
, &w
) < 0)
384 res
= PyTuple_Pack(2, v
, w
);
390 PyDoc_STRVAR(coerce_doc
,
391 "coerce(x, y) -> (x1, y1)\n\
393 Return a tuple consisting of the two numeric arguments converted to\n\
394 a common type, using the same rules as used by arithmetic operations.\n\
395 If coercion is not possible, raise TypeError.");
398 builtin_compile(PyObject
*self
, PyObject
*args
)
404 int dont_inherit
= 0;
405 int supplied_flags
= 0;
407 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
410 if (!PyArg_ParseTuple(args
, "Oss|ii:compile", &cmd
, &filename
,
411 &startstr
, &supplied_flags
, &dont_inherit
))
414 cf
.cf_flags
= supplied_flags
;
416 #ifdef Py_USING_UNICODE
417 if (PyUnicode_Check(cmd
)) {
418 tmp
= PyUnicode_AsUTF8String(cmd
);
422 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
425 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
427 if ((size_t)length
!= strlen(str
)) {
428 PyErr_SetString(PyExc_TypeError
,
429 "compile() expected string without null bytes");
433 if (strcmp(startstr
, "exec") == 0)
434 start
= Py_file_input
;
435 else if (strcmp(startstr
, "eval") == 0)
436 start
= Py_eval_input
;
437 else if (strcmp(startstr
, "single") == 0)
438 start
= Py_single_input
;
440 PyErr_SetString(PyExc_ValueError
,
441 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
446 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
))
448 PyErr_SetString(PyExc_ValueError
,
449 "compile(): unrecognised flags");
452 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
455 PyEval_MergeCompilerFlags(&cf
);
457 result
= Py_CompileStringFlags(str
, filename
, start
, &cf
);
463 PyDoc_STRVAR(compile_doc
,
464 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
466 Compile the source string (a Python module, statement or expression)\n\
467 into a code object that can be executed by the exec statement or eval().\n\
468 The filename will be used for run-time error messages.\n\
469 The mode must be 'exec' to compile a module, 'single' to compile a\n\
470 single (interactive) statement, or 'eval' to compile an expression.\n\
471 The flags argument, if present, controls which future statements influence\n\
472 the compilation of the code.\n\
473 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
474 the effects of any future statements in effect in the code calling\n\
475 compile; if absent or zero these statements do influence the compilation,\n\
476 in addition to any features explicitly specified.");
479 builtin_dir(PyObject
*self
, PyObject
*args
)
481 PyObject
*arg
= NULL
;
483 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
485 return PyObject_Dir(arg
);
488 PyDoc_STRVAR(dir_doc
,
489 "dir([object]) -> list of strings\n"
491 "Return an alphabetized list of names comprising (some of) the attributes\n"
492 "of the given object, and of attributes reachable from it:\n"
494 "No argument: the names in the current scope.\n"
495 "Module object: the module attributes.\n"
496 "Type or class object: its attributes, and recursively the attributes of\n"
498 "Otherwise: its attributes, its class's attributes, and recursively the\n"
499 " attributes of its class's base classes.");
502 builtin_divmod(PyObject
*self
, PyObject
*args
)
506 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
508 return PyNumber_Divmod(v
, w
);
511 PyDoc_STRVAR(divmod_doc
,
512 "divmod(x, y) -> (div, mod)\n\
514 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
518 builtin_eval(PyObject
*self
, PyObject
*args
)
520 PyObject
*cmd
, *result
, *tmp
= NULL
;
521 PyObject
*globals
= Py_None
, *locals
= Py_None
;
525 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
527 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
528 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
531 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
532 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
533 "globals must be a real dict; try eval(expr, {}, mapping)"
534 : "globals must be a dict");
537 if (globals
== Py_None
) {
538 globals
= PyEval_GetGlobals();
539 if (locals
== Py_None
)
540 locals
= PyEval_GetLocals();
542 else if (locals
== Py_None
)
545 if (globals
== NULL
|| locals
== NULL
) {
546 PyErr_SetString(PyExc_TypeError
,
547 "eval must be given globals and locals "
548 "when called without a frame");
552 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
553 if (PyDict_SetItemString(globals
, "__builtins__",
554 PyEval_GetBuiltins()) != 0)
558 if (PyCode_Check(cmd
)) {
559 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
560 PyErr_SetString(PyExc_TypeError
,
561 "code object passed to eval() may not contain free variables");
564 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
567 if (!PyString_Check(cmd
) &&
568 !PyUnicode_Check(cmd
)) {
569 PyErr_SetString(PyExc_TypeError
,
570 "eval() arg 1 must be a string or code object");
575 #ifdef Py_USING_UNICODE
576 if (PyUnicode_Check(cmd
)) {
577 tmp
= PyUnicode_AsUTF8String(cmd
);
581 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
584 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
588 while (*str
== ' ' || *str
== '\t')
591 (void)PyEval_MergeCompilerFlags(&cf
);
592 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
597 PyDoc_STRVAR(eval_doc
,
598 "eval(source[, globals[, locals]]) -> value\n\
600 Evaluate the source in the context of globals and locals.\n\
601 The source may be a string representing a Python expression\n\
602 or a code object as returned by compile().\n\
603 The globals must be a dictionary and locals can be any mappping,\n\
604 defaulting to the current globals and locals.\n\
605 If only globals is given, locals defaults to it.\n");
609 builtin_execfile(PyObject
*self
, PyObject
*args
)
612 PyObject
*globals
= Py_None
, *locals
= Py_None
;
618 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
620 &PyDict_Type
, &globals
,
623 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
624 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
627 if (globals
== Py_None
) {
628 globals
= PyEval_GetGlobals();
629 if (locals
== Py_None
)
630 locals
= PyEval_GetLocals();
632 else if (locals
== Py_None
)
634 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
635 if (PyDict_SetItemString(globals
, "__builtins__",
636 PyEval_GetBuiltins()) != 0)
641 /* Test for existence or directory. */
646 if ((d
= dirstat(filename
))!=nil
) {
648 werrstr("is a directory");
654 #elif defined(RISCOS)
655 if (object_exists(filename
)) {
661 #else /* standard Posix */
664 if (stat(filename
, &s
) == 0) {
665 if (S_ISDIR(s
.st_mode
))
666 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
678 Py_BEGIN_ALLOW_THREADS
679 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
688 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
692 if (PyEval_MergeCompilerFlags(&cf
))
693 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
696 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
701 PyDoc_STRVAR(execfile_doc
,
702 "execfile(filename[, globals[, locals]])\n\
704 Read and execute a Python script from a file.\n\
705 The globals and locals are dictionaries, defaulting to the current\n\
706 globals and locals. If only globals is given, locals defaults to it.");
710 builtin_getattr(PyObject
*self
, PyObject
*args
)
712 PyObject
*v
, *result
, *dflt
= NULL
;
715 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
717 #ifdef Py_USING_UNICODE
718 if (PyUnicode_Check(name
)) {
719 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
725 if (!PyString_Check(name
)) {
726 PyErr_SetString(PyExc_TypeError
,
727 "getattr(): attribute name must be string");
730 result
= PyObject_GetAttr(v
, name
);
731 if (result
== NULL
&& dflt
!= NULL
&&
732 PyErr_ExceptionMatches(PyExc_AttributeError
))
741 PyDoc_STRVAR(getattr_doc
,
742 "getattr(object, name[, default]) -> value\n\
744 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
745 When a default argument is given, it is returned when the attribute doesn't\n\
746 exist; without it, an exception is raised in that case.");
750 builtin_globals(PyObject
*self
)
754 d
= PyEval_GetGlobals();
759 PyDoc_STRVAR(globals_doc
,
760 "globals() -> dictionary\n\
762 Return the dictionary containing the current scope's global variables.");
766 builtin_hasattr(PyObject
*self
, PyObject
*args
)
771 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
773 #ifdef Py_USING_UNICODE
774 if (PyUnicode_Check(name
)) {
775 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
781 if (!PyString_Check(name
)) {
782 PyErr_SetString(PyExc_TypeError
,
783 "hasattr(): attribute name must be string");
786 v
= PyObject_GetAttr(v
, name
);
797 PyDoc_STRVAR(hasattr_doc
,
798 "hasattr(object, name) -> bool\n\
800 Return whether the object has an attribute with the given name.\n\
801 (This is done by calling getattr(object, name) and catching exceptions.)");
805 builtin_id(PyObject
*self
, PyObject
*v
)
807 return PyLong_FromVoidPtr(v
);
811 "id(object) -> integer\n\
813 Return the identity of an object. This is guaranteed to be unique among\n\
814 simultaneously existing objects. (Hint: it's the object's memory address.)");
818 builtin_map(PyObject
*self
, PyObject
*args
)
821 PyObject
*it
; /* the iterator object */
822 int saw_StopIteration
; /* bool: did the iterator end? */
825 PyObject
*func
, *result
;
826 sequence
*seqs
= NULL
, *sqp
;
830 n
= PyTuple_Size(args
);
832 PyErr_SetString(PyExc_TypeError
,
833 "map() requires at least two args");
837 func
= PyTuple_GetItem(args
, 0);
840 if (func
== Py_None
&& n
== 1) {
841 /* map(None, S) is the same as list(S). */
842 return PySequence_List(PyTuple_GetItem(args
, 1));
845 /* Get space for sequence descriptors. Must NULL out the iterator
846 * pointers so that jumping to Fail_2 later doesn't see trash.
848 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
852 for (i
= 0; i
< n
; ++i
) {
853 seqs
[i
].it
= (PyObject
*)NULL
;
854 seqs
[i
].saw_StopIteration
= 0;
857 /* Do a first pass to obtain iterators for the arguments, and set len
858 * to the largest of their lengths.
861 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
866 curseq
= PyTuple_GetItem(args
, i
+1);
867 sqp
->it
= PyObject_GetIter(curseq
);
868 if (sqp
->it
== NULL
) {
869 static char errmsg
[] =
870 "argument %d to map() must support iteration";
871 char errbuf
[sizeof(errmsg
) + 25];
872 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
873 PyErr_SetString(PyExc_TypeError
, errbuf
);
878 curlen
= _PyObject_LengthCue(curseq
);
880 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
881 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
885 curlen
= 8; /* arbitrary */
891 /* Get space for the result list. */
892 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
895 /* Iterate over the sequences until all have stopped. */
897 PyObject
*alist
, *item
=NULL
, *value
;
900 if (func
== Py_None
&& n
== 1)
902 else if ((alist
= PyTuple_New(n
)) == NULL
)
905 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
906 if (sqp
->saw_StopIteration
) {
911 item
= PyIter_Next(sqp
->it
);
915 if (PyErr_Occurred()) {
921 sqp
->saw_StopIteration
= 1;
925 PyTuple_SET_ITEM(alist
, j
, item
);
933 if (numactive
== 0) {
941 value
= PyEval_CallObject(func
, alist
);
947 int status
= PyList_Append(result
, value
);
952 else if (PyList_SetItem(result
, i
, value
) < 0)
956 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
967 for (i
= 0; i
< n
; ++i
)
968 Py_XDECREF(seqs
[i
].it
);
973 PyDoc_STRVAR(map_doc
,
974 "map(function, sequence[, sequence, ...]) -> list\n\
976 Return a list of the results of applying the function to the items of\n\
977 the argument sequence(s). If more than one sequence is given, the\n\
978 function is called with an argument list consisting of the corresponding\n\
979 item of each sequence, substituting None for missing values when not all\n\
980 sequences have the same length. If the function is None, return a list of\n\
981 the items of the sequence (or a list of tuples if more than one sequence).");
985 builtin_setattr(PyObject
*self
, PyObject
*args
)
991 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
993 if (PyObject_SetAttr(v
, name
, value
) != 0)
999 PyDoc_STRVAR(setattr_doc
,
1000 "setattr(object, name, value)\n\
1002 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1007 builtin_delattr(PyObject
*self
, PyObject
*args
)
1012 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1014 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1020 PyDoc_STRVAR(delattr_doc
,
1021 "delattr(object, name)\n\
1023 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1028 builtin_hash(PyObject
*self
, PyObject
*v
)
1032 x
= PyObject_Hash(v
);
1035 return PyInt_FromLong(x
);
1038 PyDoc_STRVAR(hash_doc
,
1039 "hash(object) -> integer\n\
1041 Return a hash value for the object. Two objects with the same value have\n\
1042 the same hash value. The reverse is not necessarily true, but likely.");
1046 builtin_hex(PyObject
*self
, PyObject
*v
)
1048 PyNumberMethods
*nb
;
1051 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1052 nb
->nb_hex
== NULL
) {
1053 PyErr_SetString(PyExc_TypeError
,
1054 "hex() argument can't be converted to hex");
1057 res
= (*nb
->nb_hex
)(v
);
1058 if (res
&& !PyString_Check(res
)) {
1059 PyErr_Format(PyExc_TypeError
,
1060 "__hex__ returned non-string (type %.200s)",
1061 res
->ob_type
->tp_name
);
1068 PyDoc_STRVAR(hex_doc
,
1069 "hex(number) -> string\n\
1071 Return the hexadecimal representation of an integer or long integer.");
1074 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1077 builtin_input(PyObject
*self
, PyObject
*args
)
1082 PyObject
*globals
, *locals
;
1085 line
= builtin_raw_input(self
, args
);
1088 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1090 while (*str
== ' ' || *str
== '\t')
1092 globals
= PyEval_GetGlobals();
1093 locals
= PyEval_GetLocals();
1094 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1095 if (PyDict_SetItemString(globals
, "__builtins__",
1096 PyEval_GetBuiltins()) != 0)
1100 PyEval_MergeCompilerFlags(&cf
);
1101 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1106 PyDoc_STRVAR(input_doc
,
1107 "input([prompt]) -> value\n\
1109 Equivalent to eval(raw_input(prompt)).");
1113 builtin_intern(PyObject
*self
, PyObject
*args
)
1116 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1118 if (!PyString_CheckExact(s
)) {
1119 PyErr_SetString(PyExc_TypeError
,
1120 "can't intern subclass of string");
1124 PyString_InternInPlace(&s
);
1128 PyDoc_STRVAR(intern_doc
,
1129 "intern(string) -> string\n\
1131 ``Intern'' the given string. This enters the string in the (global)\n\
1132 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1133 Return the string itself or the previously interned string object with the\n\
1138 builtin_iter(PyObject
*self
, PyObject
*args
)
1140 PyObject
*v
, *w
= NULL
;
1142 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1145 return PyObject_GetIter(v
);
1146 if (!PyCallable_Check(v
)) {
1147 PyErr_SetString(PyExc_TypeError
,
1148 "iter(v, w): v must be callable");
1151 return PyCallIter_New(v
, w
);
1154 PyDoc_STRVAR(iter_doc
,
1155 "iter(collection) -> iterator\n\
1156 iter(callable, sentinel) -> iterator\n\
1158 Get an iterator from an object. In the first form, the argument must\n\
1159 supply its own iterator, or be a sequence.\n\
1160 In the second form, the callable is called until it returns the sentinel.");
1164 builtin_len(PyObject
*self
, PyObject
*v
)
1168 res
= PyObject_Size(v
);
1169 if (res
< 0 && PyErr_Occurred())
1171 return PyInt_FromLong(res
);
1174 PyDoc_STRVAR(len_doc
,
1175 "len(object) -> integer\n\
1177 Return the number of items of a sequence or mapping.");
1181 builtin_locals(PyObject
*self
)
1185 d
= PyEval_GetLocals();
1190 PyDoc_STRVAR(locals_doc
,
1191 "locals() -> dictionary\n\
1193 Update and return a dictionary containing the current scope's local variables.");
1197 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1199 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1200 const char *name
= op
== Py_LT
? "min" : "max";
1202 if (PyTuple_Size(args
) > 1)
1204 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1207 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1208 keyfunc
= PyDict_GetItemString(kwds
, "key");
1209 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1210 PyErr_Format(PyExc_TypeError
,
1211 "%s() got an unexpected keyword argument", name
);
1216 it
= PyObject_GetIter(v
);
1220 maxitem
= NULL
; /* the result */
1221 maxval
= NULL
; /* the value associated with the result */
1222 while (( item
= PyIter_Next(it
) )) {
1223 /* get the value from the key function */
1224 if (keyfunc
!= NULL
) {
1225 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1229 /* no key function; the value is the item */
1235 /* maximum value and item are unset; set them */
1236 if (maxval
== NULL
) {
1240 /* maximum value and item are set; update them as necessary */
1242 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1244 goto Fail_it_item_and_val
;
1257 if (PyErr_Occurred())
1259 if (maxval
== NULL
) {
1260 PyErr_Format(PyExc_ValueError
,
1261 "%s() arg is an empty sequence", name
);
1262 assert(maxitem
== NULL
);
1269 Fail_it_item_and_val
:
1275 Py_XDECREF(maxitem
);
1281 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1283 return min_max(args
, kwds
, Py_LT
);
1286 PyDoc_STRVAR(min_doc
,
1287 "min(iterable[, key=func]) -> value\n\
1288 min(a, b, c, ...[, key=func]) -> value\n\
1290 With a single iterable argument, return its smallest item.\n\
1291 With two or more arguments, return the smallest argument.");
1295 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1297 return min_max(args
, kwds
, Py_GT
);
1300 PyDoc_STRVAR(max_doc
,
1301 "max(iterable[, key=func]) -> value\n\
1302 max(a, b, c, ...[, key=func]) -> value\n\
1304 With a single iterable argument, return its largest item.\n\
1305 With two or more arguments, return the largest argument.");
1309 builtin_oct(PyObject
*self
, PyObject
*v
)
1311 PyNumberMethods
*nb
;
1314 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1315 nb
->nb_oct
== NULL
) {
1316 PyErr_SetString(PyExc_TypeError
,
1317 "oct() argument can't be converted to oct");
1320 res
= (*nb
->nb_oct
)(v
);
1321 if (res
&& !PyString_Check(res
)) {
1322 PyErr_Format(PyExc_TypeError
,
1323 "__oct__ returned non-string (type %.200s)",
1324 res
->ob_type
->tp_name
);
1331 PyDoc_STRVAR(oct_doc
,
1332 "oct(number) -> string\n\
1334 Return the octal representation of an integer or long integer.");
1338 builtin_ord(PyObject
*self
, PyObject
* obj
)
1343 if (PyString_Check(obj
)) {
1344 size
= PyString_GET_SIZE(obj
);
1346 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1347 return PyInt_FromLong(ord
);
1349 #ifdef Py_USING_UNICODE
1350 } else if (PyUnicode_Check(obj
)) {
1351 size
= PyUnicode_GET_SIZE(obj
);
1353 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1354 return PyInt_FromLong(ord
);
1358 PyErr_Format(PyExc_TypeError
,
1359 "ord() expected string of length 1, but " \
1360 "%.200s found", obj
->ob_type
->tp_name
);
1364 PyErr_Format(PyExc_TypeError
,
1365 "ord() expected a character, "
1366 "but string of length %d found",
1371 PyDoc_STRVAR(ord_doc
,
1372 "ord(c) -> integer\n\
1374 Return the integer ordinal of a one-character string.");
1378 builtin_pow(PyObject
*self
, PyObject
*args
)
1380 PyObject
*v
, *w
, *z
= Py_None
;
1382 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1384 return PyNumber_Power(v
, w
, z
);
1387 PyDoc_STRVAR(pow_doc
,
1388 "pow(x, y[, z]) -> number\n\
1390 With two arguments, equivalent to x**y. With three arguments,\n\
1391 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1395 /* Return number of items in range (lo, hi, step), when arguments are
1396 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1397 * & only if the true value is too large to fit in a signed long.
1398 * Arguments MUST return 1 with either PyInt_Check() or
1399 * PyLong_Check(). Return -1 when there is an error.
1402 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1404 /* -------------------------------------------------------------
1405 Algorithm is equal to that of get_len_of_range(), but it operates
1406 on PyObjects (which are assumed to be PyLong or PyInt objects).
1407 ---------------------------------------------------------------*/
1409 PyObject
*diff
= NULL
;
1410 PyObject
*one
= NULL
;
1411 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1412 /* holds sub-expression evaluations */
1414 /* if (lo >= hi), return length of 0. */
1415 if (PyObject_Compare(lo
, hi
) >= 0)
1418 if ((one
= PyLong_FromLong(1L)) == NULL
)
1421 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1424 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1427 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1430 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1433 n
= PyLong_AsLong(tmp3
);
1434 if (PyErr_Occurred()) { /* Check for Overflow */
1455 /* An extension of builtin_range() that handles the case when PyLong
1456 * arguments are given. */
1458 handle_range_longs(PyObject
*self
, PyObject
*args
)
1461 PyObject
*ihigh
= NULL
;
1462 PyObject
*istep
= NULL
;
1464 PyObject
*curnum
= NULL
;
1470 PyObject
*zero
= PyLong_FromLong(0);
1475 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1480 /* Figure out which way we were called, supply defaults, and be
1481 * sure to incref everything so that the decrefs at the end
1484 assert(ilow
!= NULL
);
1485 if (ihigh
== NULL
) {
1486 /* only 1 arg -- it's the upper limit */
1490 assert(ihigh
!= NULL
);
1493 /* ihigh correct now; do ilow */
1498 /* ilow and ihigh correct now; do istep */
1499 if (istep
== NULL
) {
1500 istep
= PyLong_FromLong(1L);
1508 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1509 PyErr_Format(PyExc_TypeError
,
1510 "range() integer start argument expected, got %s.",
1511 ilow
->ob_type
->tp_name
);
1515 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1516 PyErr_Format(PyExc_TypeError
,
1517 "range() integer end argument expected, got %s.",
1518 ihigh
->ob_type
->tp_name
);
1522 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1523 PyErr_Format(PyExc_TypeError
,
1524 "range() integer step argument expected, got %s.",
1525 istep
->ob_type
->tp_name
);
1529 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1531 if (cmp_result
== 0) {
1532 PyErr_SetString(PyExc_ValueError
,
1533 "range() step argument must not be zero");
1538 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1540 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1541 if (neg_istep
== NULL
)
1543 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1544 Py_DECREF(neg_istep
);
1548 if (bign
< 0 || (long)n
!= bign
) {
1549 PyErr_SetString(PyExc_OverflowError
,
1550 "range() result has too many items");
1561 for (i
= 0; i
< n
; i
++) {
1562 PyObject
*w
= PyNumber_Long(curnum
);
1567 PyList_SET_ITEM(v
, i
, w
);
1569 tmp_num
= PyNumber_Add(curnum
, istep
);
1570 if (tmp_num
== NULL
)
1593 /* Return number of items in range/xrange (lo, hi, step). step > 0
1594 * required. Return a value < 0 if & only if the true value is too
1595 * large to fit in a signed long.
1598 get_len_of_range(long lo
, long hi
, long step
)
1600 /* -------------------------------------------------------------
1601 If lo >= hi, the range is empty.
1602 Else if n values are in the range, the last one is
1603 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1604 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1605 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1606 the RHS is non-negative and so truncation is the same as the
1607 floor. Letting M be the largest positive long, the worst case
1608 for the RHS numerator is hi=M, lo=-M-1, and then
1609 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1610 precision to compute the RHS exactly.
1611 ---------------------------------------------------------------*/
1614 unsigned long uhi
= (unsigned long)hi
;
1615 unsigned long ulo
= (unsigned long)lo
;
1616 unsigned long diff
= uhi
- ulo
- 1;
1617 n
= (long)(diff
/ (unsigned long)step
+ 1);
1623 builtin_range(PyObject
*self
, PyObject
*args
)
1625 long ilow
= 0, ihigh
= 0, istep
= 1;
1631 if (PyTuple_Size(args
) <= 1) {
1632 if (!PyArg_ParseTuple(args
,
1633 "l;range() requires 1-3 int arguments",
1636 return handle_range_longs(self
, args
);
1640 if (!PyArg_ParseTuple(args
,
1641 "ll|l;range() requires 1-3 int arguments",
1642 &ilow
, &ihigh
, &istep
)) {
1644 return handle_range_longs(self
, args
);
1648 PyErr_SetString(PyExc_ValueError
,
1649 "range() step argument must not be zero");
1653 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1655 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1657 if (bign
< 0 || (long)n
!= bign
) {
1658 PyErr_SetString(PyExc_OverflowError
,
1659 "range() result has too many items");
1665 for (i
= 0; i
< n
; i
++) {
1666 PyObject
*w
= PyInt_FromLong(ilow
);
1671 PyList_SET_ITEM(v
, i
, w
);
1677 PyDoc_STRVAR(range_doc
,
1678 "range([start,] stop[, step]) -> list of integers\n\
1680 Return a list containing an arithmetic progression of integers.\n\
1681 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1682 When step is given, it specifies the increment (or decrement).\n\
1683 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1684 These are exactly the valid indices for a list of 4 elements.");
1688 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1691 PyObject
*fin
= PySys_GetObject("stdin");
1692 PyObject
*fout
= PySys_GetObject("stdout");
1694 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1698 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1702 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1705 if (PyFile_SoftSpace(fout
, 0)) {
1706 if (PyFile_WriteString(" ", fout
) != 0)
1709 if (PyFile_Check(fin
) && PyFile_Check(fout
)
1710 && isatty(fileno(PyFile_AsFile(fin
)))
1711 && isatty(fileno(PyFile_AsFile(fout
)))) {
1717 po
= PyObject_Str(v
);
1720 prompt
= PyString_AsString(po
);
1728 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
1732 if (!PyErr_Occurred())
1733 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1737 PyErr_SetNone(PyExc_EOFError
);
1740 else { /* strip trailing '\n' */
1741 size_t len
= strlen(s
);
1742 if (len
> INT_MAX
) {
1743 PyErr_SetString(PyExc_OverflowError
,
1744 "[raw_]input: input too long");
1748 result
= PyString_FromStringAndSize(s
,
1756 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
1759 return PyFile_GetLine(fin
, -1);
1762 PyDoc_STRVAR(raw_input_doc
,
1763 "raw_input([prompt]) -> string\n\
1765 Read a string from standard input. The trailing newline is stripped.\n\
1766 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1767 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1768 is printed without a trailing newline before reading.");
1772 builtin_reduce(PyObject
*self
, PyObject
*args
)
1774 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1776 if (!PyArg_UnpackTuple(args
, "reduce", 2, 3, &func
, &seq
, &result
))
1781 it
= PyObject_GetIter(seq
);
1783 PyErr_SetString(PyExc_TypeError
,
1784 "reduce() arg 2 must support iteration");
1789 if ((args
= PyTuple_New(2)) == NULL
)
1795 if (args
->ob_refcnt
> 1) {
1797 if ((args
= PyTuple_New(2)) == NULL
)
1801 op2
= PyIter_Next(it
);
1803 if (PyErr_Occurred())
1811 PyTuple_SetItem(args
, 0, result
);
1812 PyTuple_SetItem(args
, 1, op2
);
1813 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1821 PyErr_SetString(PyExc_TypeError
,
1822 "reduce() of empty sequence with no initial value");
1834 PyDoc_STRVAR(reduce_doc
,
1835 "reduce(function, sequence[, initial]) -> value\n\
1837 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1838 from left to right, so as to reduce the sequence to a single value.\n\
1839 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1840 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1841 of the sequence in the calculation, and serves as a default when the\n\
1842 sequence is empty.");
1846 builtin_reload(PyObject
*self
, PyObject
*v
)
1848 return PyImport_ReloadModule(v
);
1851 PyDoc_STRVAR(reload_doc
,
1852 "reload(module) -> module\n\
1854 Reload the module. The module must have been successfully imported before.");
1858 builtin_repr(PyObject
*self
, PyObject
*v
)
1860 return PyObject_Repr(v
);
1863 PyDoc_STRVAR(repr_doc
,
1864 "repr(object) -> string\n\
1866 Return the canonical string representation of the object.\n\
1867 For most object types, eval(repr(object)) == object.");
1871 builtin_round(PyObject
*self
, PyObject
*args
)
1878 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1896 return PyFloat_FromDouble(x
);
1899 PyDoc_STRVAR(round_doc
,
1900 "round(number[, ndigits]) -> floating point number\n\
1902 Round a number to a given precision in decimal digits (default 0 digits).\n\
1903 This always returns a floating point number. Precision may be negative.");
1906 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1908 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
1910 static const char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
1913 /* args 1-4 should match listsort in Objects/listobject.c */
1914 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
1915 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
1918 newlist
= PySequence_List(seq
);
1919 if (newlist
== NULL
)
1922 callable
= PyObject_GetAttrString(newlist
, "sort");
1923 if (callable
== NULL
) {
1928 newargs
= PyTuple_GetSlice(args
, 1, 4);
1929 if (newargs
== NULL
) {
1931 Py_DECREF(callable
);
1935 v
= PyObject_Call(callable
, newargs
, kwds
);
1937 Py_DECREF(callable
);
1946 PyDoc_STRVAR(sorted_doc
,
1947 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
1950 builtin_vars(PyObject
*self
, PyObject
*args
)
1955 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
1958 d
= PyEval_GetLocals();
1960 if (!PyErr_Occurred())
1961 PyErr_SetString(PyExc_SystemError
,
1962 "vars(): no locals!?");
1968 d
= PyObject_GetAttrString(v
, "__dict__");
1970 PyErr_SetString(PyExc_TypeError
,
1971 "vars() argument must have __dict__ attribute");
1978 PyDoc_STRVAR(vars_doc
,
1979 "vars([object]) -> dictionary\n\
1981 Without arguments, equivalent to locals().\n\
1982 With an argument, equivalent to object.__dict__.");
1986 builtin_sum(PyObject
*self
, PyObject
*args
)
1989 PyObject
*result
= NULL
;
1990 PyObject
*temp
, *item
, *iter
;
1992 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
1995 iter
= PyObject_GetIter(seq
);
1999 if (result
== NULL
) {
2000 result
= PyInt_FromLong(0);
2001 if (result
== NULL
) {
2006 /* reject string values for 'start' parameter */
2007 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2008 PyErr_SetString(PyExc_TypeError
,
2009 "sum() can't sum strings [use ''.join(seq) instead]");
2017 item
= PyIter_Next(iter
);
2019 /* error, or end-of-sequence */
2020 if (PyErr_Occurred()) {
2026 temp
= PyNumber_Add(result
, item
);
2037 PyDoc_STRVAR(sum_doc
,
2038 "sum(sequence, start=0) -> value\n\
2040 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2041 of parameter 'start'. When the sequence is empty, returns start.");
2045 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2051 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2054 retval
= PyObject_IsInstance(inst
, cls
);
2057 return PyBool_FromLong(retval
);
2060 PyDoc_STRVAR(isinstance_doc
,
2061 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2063 Return whether an object is an instance of a class or of a subclass thereof.\n\
2064 With a type as second argument, return whether that is the object's type.\n\
2065 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2066 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2070 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2076 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2079 retval
= PyObject_IsSubclass(derived
, cls
);
2082 return PyBool_FromLong(retval
);
2085 PyDoc_STRVAR(issubclass_doc
,
2086 "issubclass(C, B) -> bool\n\
2088 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2089 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2090 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2094 builtin_zip(PyObject
*self
, PyObject
*args
)
2097 const int itemsize
= PySequence_Length(args
);
2099 PyObject
*itlist
; /* tuple of iterators */
2100 int len
; /* guess at result length */
2103 return PyList_New(0);
2105 /* args must be a tuple */
2106 assert(PyTuple_Check(args
));
2108 /* Guess at result length: the shortest of the input lengths.
2109 If some argument refuses to say, we refuse to guess too, lest
2110 an argument like xrange(sys.maxint) lead us astray.*/
2111 len
= -1; /* unknown */
2112 for (i
= 0; i
< itemsize
; ++i
) {
2113 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2114 int thislen
= _PyObject_LengthCue(item
);
2116 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
2117 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
2124 else if (len
< 0 || thislen
< len
)
2128 /* allocate result list */
2130 len
= 10; /* arbitrary */
2131 if ((ret
= PyList_New(len
)) == NULL
)
2134 /* obtain iterators */
2135 itlist
= PyTuple_New(itemsize
);
2138 for (i
= 0; i
< itemsize
; ++i
) {
2139 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2140 PyObject
*it
= PyObject_GetIter(item
);
2142 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2143 PyErr_Format(PyExc_TypeError
,
2144 "zip argument #%d must support iteration",
2146 goto Fail_ret_itlist
;
2148 PyTuple_SET_ITEM(itlist
, i
, it
);
2151 /* build result into ret list */
2152 for (i
= 0; ; ++i
) {
2154 PyObject
*next
= PyTuple_New(itemsize
);
2156 goto Fail_ret_itlist
;
2158 for (j
= 0; j
< itemsize
; j
++) {
2159 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2160 PyObject
*item
= PyIter_Next(it
);
2162 if (PyErr_Occurred()) {
2170 PyTuple_SET_ITEM(next
, j
, item
);
2174 PyList_SET_ITEM(ret
, i
, next
);
2176 int status
= PyList_Append(ret
, next
);
2180 goto Fail_ret_itlist
;
2185 if (ret
!= NULL
&& i
< len
) {
2186 /* The list is too big. */
2187 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2200 PyDoc_STRVAR(zip_doc
,
2201 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2203 Return a list of tuples, where each tuple contains the i-th element\n\
2204 from each of the argument sequences. The returned list is truncated\n\
2205 in length to the length of the shortest argument sequence.");
2208 static PyMethodDef builtin_methods
[] = {
2209 {"__import__", builtin___import__
, METH_VARARGS
, import_doc
},
2210 {"abs", builtin_abs
, METH_O
, abs_doc
},
2211 {"all", builtin_all
, METH_O
, all_doc
},
2212 {"any", builtin_any
, METH_O
, any_doc
},
2213 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2214 {"callable", builtin_callable
, METH_O
, callable_doc
},
2215 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2216 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2217 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2218 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
2219 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2220 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2221 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2222 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2223 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2224 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2225 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2226 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2227 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2228 {"hash", builtin_hash
, METH_O
, hash_doc
},
2229 {"hex", builtin_hex
, METH_O
, hex_doc
},
2230 {"id", builtin_id
, METH_O
, id_doc
},
2231 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2232 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2233 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2234 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2235 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2236 {"len", builtin_len
, METH_O
, len_doc
},
2237 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2238 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2239 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2240 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2241 {"oct", builtin_oct
, METH_O
, oct_doc
},
2242 {"ord", builtin_ord
, METH_O
, ord_doc
},
2243 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2244 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2245 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2246 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2247 {"reload", builtin_reload
, METH_O
, reload_doc
},
2248 {"repr", builtin_repr
, METH_O
, repr_doc
},
2249 {"round", builtin_round
, METH_VARARGS
, round_doc
},
2250 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2251 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2252 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2253 #ifdef Py_USING_UNICODE
2254 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2256 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2257 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2261 PyDoc_STRVAR(builtin_doc
,
2262 "Built-in functions, exceptions, and other objects.\n\
2264 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2267 _PyBuiltin_Init(void)
2269 PyObject
*mod
, *dict
, *debug
;
2270 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2271 builtin_doc
, (PyObject
*)NULL
,
2272 PYTHON_API_VERSION
);
2275 dict
= PyModule_GetDict(mod
);
2277 #ifdef Py_TRACE_REFS
2278 /* __builtin__ exposes a number of statically allocated objects
2279 * that, before this code was added in 2.3, never showed up in
2280 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2281 * result, programs leaking references to None and False (etc)
2282 * couldn't be diagnosed by examining sys.getobjects(0).
2284 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2286 #define ADD_TO_ALL(OBJECT) (void)0
2289 #define SETBUILTIN(NAME, OBJECT) \
2290 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2294 SETBUILTIN("None", Py_None
);
2295 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2296 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2297 SETBUILTIN("False", Py_False
);
2298 SETBUILTIN("True", Py_True
);
2299 SETBUILTIN("basestring", &PyBaseString_Type
);
2300 SETBUILTIN("bool", &PyBool_Type
);
2301 SETBUILTIN("buffer", &PyBuffer_Type
);
2302 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2303 #ifndef WITHOUT_COMPLEX
2304 SETBUILTIN("complex", &PyComplex_Type
);
2306 SETBUILTIN("dict", &PyDict_Type
);
2307 SETBUILTIN("enumerate", &PyEnum_Type
);
2308 SETBUILTIN("float", &PyFloat_Type
);
2309 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2310 SETBUILTIN("property", &PyProperty_Type
);
2311 SETBUILTIN("int", &PyInt_Type
);
2312 SETBUILTIN("list", &PyList_Type
);
2313 SETBUILTIN("long", &PyLong_Type
);
2314 SETBUILTIN("object", &PyBaseObject_Type
);
2315 SETBUILTIN("reversed", &PyReversed_Type
);
2316 SETBUILTIN("set", &PySet_Type
);
2317 SETBUILTIN("slice", &PySlice_Type
);
2318 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2319 SETBUILTIN("str", &PyString_Type
);
2320 SETBUILTIN("super", &PySuper_Type
);
2321 SETBUILTIN("tuple", &PyTuple_Type
);
2322 SETBUILTIN("type", &PyType_Type
);
2323 SETBUILTIN("xrange", &PyRange_Type
);
2325 /* Note that open() is just an alias of file(). */
2326 SETBUILTIN("open", &PyFile_Type
);
2327 SETBUILTIN("file", &PyFile_Type
);
2328 #ifdef Py_USING_UNICODE
2329 SETBUILTIN("unicode", &PyUnicode_Type
);
2331 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2332 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2343 /* Helper for filter(): filter a tuple through a function */
2346 filtertuple(PyObject
*func
, PyObject
*tuple
)
2350 int len
= PyTuple_Size(tuple
);
2353 if (PyTuple_CheckExact(tuple
))
2356 tuple
= PyTuple_New(0);
2360 if ((result
= PyTuple_New(len
)) == NULL
)
2363 for (i
= j
= 0; i
< len
; ++i
) {
2364 PyObject
*item
, *good
;
2367 if (tuple
->ob_type
->tp_as_sequence
&&
2368 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2369 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2373 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2376 if (func
== Py_None
) {
2381 PyObject
*arg
= PyTuple_Pack(1, item
);
2386 good
= PyEval_CallObject(func
, arg
);
2393 ok
= PyObject_IsTrue(good
);
2396 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2403 if (_PyTuple_Resize(&result
, j
) < 0)
2414 /* Helper for filter(): filter a string through a function */
2417 filterstring(PyObject
*func
, PyObject
*strobj
)
2421 int len
= PyString_Size(strobj
);
2424 if (func
== Py_None
) {
2425 /* If it's a real string we can return the original,
2426 * as no character is ever false and __getitem__
2427 * does return this character. If it's a subclass
2428 * we must go through the __getitem__ loop */
2429 if (PyString_CheckExact(strobj
)) {
2434 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2437 for (i
= j
= 0; i
< len
; ++i
) {
2441 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2444 if (func
==Py_None
) {
2447 PyObject
*arg
, *good
;
2448 arg
= PyTuple_Pack(1, item
);
2453 good
= PyEval_CallObject(func
, arg
);
2459 ok
= PyObject_IsTrue(good
);
2464 if (!PyString_Check(item
)) {
2465 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2466 " __getitem__ returned different type");
2470 reslen
= PyString_GET_SIZE(item
);
2472 PyString_AS_STRING(result
)[j
++] =
2473 PyString_AS_STRING(item
)[0];
2475 /* do we need more space? */
2476 int need
= j
+ reslen
+ len
-i
-1;
2477 if (need
> outlen
) {
2478 /* overallocate, to avoid reallocations */
2481 if (_PyString_Resize(&result
, need
)) {
2488 PyString_AS_STRING(result
) + j
,
2489 PyString_AS_STRING(item
),
2499 _PyString_Resize(&result
, j
);
2508 #ifdef Py_USING_UNICODE
2509 /* Helper for filter(): filter a Unicode object through a function */
2512 filterunicode(PyObject
*func
, PyObject
*strobj
)
2516 int len
= PyUnicode_GetSize(strobj
);
2519 if (func
== Py_None
) {
2520 /* If it's a real string we can return the original,
2521 * as no character is ever false and __getitem__
2522 * does return this character. If it's a subclass
2523 * we must go through the __getitem__ loop */
2524 if (PyUnicode_CheckExact(strobj
)) {
2529 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2532 for (i
= j
= 0; i
< len
; ++i
) {
2533 PyObject
*item
, *arg
, *good
;
2536 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2539 if (func
== Py_None
) {
2542 arg
= PyTuple_Pack(1, item
);
2547 good
= PyEval_CallObject(func
, arg
);
2553 ok
= PyObject_IsTrue(good
);
2558 if (!PyUnicode_Check(item
)) {
2559 PyErr_SetString(PyExc_TypeError
,
2560 "can't filter unicode to unicode:"
2561 " __getitem__ returned different type");
2565 reslen
= PyUnicode_GET_SIZE(item
);
2567 PyUnicode_AS_UNICODE(result
)[j
++] =
2568 PyUnicode_AS_UNICODE(item
)[0];
2570 /* do we need more space? */
2571 int need
= j
+ reslen
+ len
- i
- 1;
2572 if (need
> outlen
) {
2574 to avoid reallocations */
2575 if (need
< 2 * outlen
)
2577 if (PyUnicode_Resize(
2578 &result
, need
) < 0) {
2584 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2585 PyUnicode_AS_UNICODE(item
),
2586 reslen
*sizeof(Py_UNICODE
));
2594 PyUnicode_Resize(&result
, j
);