2 /* Built-in functions */
13 #include "unixstuff.h"
16 /* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
19 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding
= "mbcs";
21 #elif defined(__APPLE__)
22 const char *Py_FileSystemDefaultEncoding
= "utf-8";
24 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
28 static PyObject
*filterstring(PyObject
*, PyObject
*);
29 #ifdef Py_USING_UNICODE
30 static PyObject
*filterunicode(PyObject
*, PyObject
*);
32 static PyObject
*filtertuple (PyObject
*, PyObject
*);
35 builtin___import__(PyObject
*self
, PyObject
*args
)
38 PyObject
*globals
= NULL
;
39 PyObject
*locals
= NULL
;
40 PyObject
*fromlist
= NULL
;
42 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
43 &name
, &globals
, &locals
, &fromlist
))
45 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
48 PyDoc_STRVAR(import_doc
,
49 "__import__(name, globals, locals, fromlist) -> module\n\
51 Import a module. The globals are only used to determine the context;\n\
52 they are not modified. The locals are currently unused. The fromlist\n\
53 should be a list of names to emulate ``from name import ...'', or an\n\
54 empty list to emulate ``import name''.\n\
55 When importing a module from a package, note that __import__('A.B', ...)\n\
56 returns package A when fromlist is empty, but its submodule B when\n\
57 fromlist is not empty.");
61 builtin_abs(PyObject
*self
, PyObject
*v
)
63 return PyNumber_Absolute(v
);
67 "abs(number) -> number\n\
69 Return the absolute value of the argument.");
73 builtin_apply(PyObject
*self
, PyObject
*args
)
75 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
76 PyObject
*t
= NULL
, *retval
= NULL
;
78 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
81 if (!PyTuple_Check(alist
)) {
82 if (!PySequence_Check(alist
)) {
83 PyErr_Format(PyExc_TypeError
,
84 "apply() arg 2 expected sequence, found %s",
85 alist
->ob_type
->tp_name
);
88 t
= PySequence_Tuple(alist
);
94 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
95 PyErr_Format(PyExc_TypeError
,
96 "apply() arg 3 expected dictionary, found %s",
97 kwdict
->ob_type
->tp_name
);
100 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
106 PyDoc_STRVAR(apply_doc
,
107 "apply(object[, args[, kwargs]]) -> value\n\
109 Call a callable object with positional arguments taken from the tuple args,\n\
110 and keyword arguments taken from the optional dictionary kwargs.\n\
111 Note that classes are callable, as are instances with a __call__() method.\n\
113 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
114 function(*args, **keywords).");
118 builtin_callable(PyObject
*self
, PyObject
*v
)
120 return PyBool_FromLong((long)PyCallable_Check(v
));
123 PyDoc_STRVAR(callable_doc
,
124 "callable(object) -> bool\n\
126 Return whether the object is callable (i.e., some kind of function).\n\
127 Note that classes are callable, as are instances with a __call__() method.");
131 builtin_filter(PyObject
*self
, PyObject
*args
)
133 PyObject
*func
, *seq
, *result
, *it
, *arg
;
134 int len
; /* guess for result list size */
137 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
140 /* Strings and tuples return a result of the same type. */
141 if (PyString_Check(seq
))
142 return filterstring(func
, seq
);
143 #ifdef Py_USING_UNICODE
144 if (PyUnicode_Check(seq
))
145 return filterunicode(func
, seq
);
147 if (PyTuple_Check(seq
))
148 return filtertuple(func
, seq
);
151 it
= PyObject_GetIter(seq
);
155 /* Guess a result list size. */
156 len
= PyObject_Size(seq
);
159 len
= 8; /* arbitrary */
162 /* Pre-allocate argument list tuple. */
163 arg
= PyTuple_New(1);
167 /* Get a result list. */
168 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
169 /* Eww - can modify the list in-place. */
174 result
= PyList_New(len
);
179 /* Build the result list. */
185 item
= PyIter_Next(it
);
187 if (PyErr_Occurred())
192 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
193 ok
= PyObject_IsTrue(item
);
197 PyTuple_SET_ITEM(arg
, 0, item
);
198 good
= PyObject_Call(func
, arg
, NULL
);
199 PyTuple_SET_ITEM(arg
, 0, NULL
);
204 ok
= PyObject_IsTrue(good
);
209 PyList_SET_ITEM(result
, j
, item
);
211 int status
= PyList_Append(result
, item
);
223 /* Cut back result list if len is too big. */
224 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
240 PyDoc_STRVAR(filter_doc
,
241 "filter(function or None, sequence) -> list, tuple, or string\n"
243 "Return those items of sequence for which function(item) is true. If\n"
244 "function is None, return the items that are true. If sequence is a tuple\n"
245 "or string, return the same type, else return a list.");
248 builtin_chr(PyObject
*self
, PyObject
*args
)
253 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
255 if (x
< 0 || x
>= 256) {
256 PyErr_SetString(PyExc_ValueError
,
257 "chr() arg not in range(256)");
261 return PyString_FromStringAndSize(s
, 1);
264 PyDoc_STRVAR(chr_doc
,
265 "chr(i) -> character\n\
267 Return a string of one character with ordinal i; 0 <= i < 256.");
270 #ifdef Py_USING_UNICODE
272 builtin_unichr(PyObject
*self
, PyObject
*args
)
276 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
279 return PyUnicode_FromOrdinal(x
);
282 PyDoc_STRVAR(unichr_doc
,
283 "unichr(i) -> Unicode character\n\
285 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
290 builtin_cmp(PyObject
*self
, PyObject
*args
)
295 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
297 if (PyObject_Cmp(a
, b
, &c
) < 0)
299 return PyInt_FromLong((long)c
);
302 PyDoc_STRVAR(cmp_doc
,
303 "cmp(x, y) -> integer\n\
305 Return negative if x<y, zero if x==y, positive if x>y.");
309 builtin_coerce(PyObject
*self
, PyObject
*args
)
314 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
316 if (PyNumber_Coerce(&v
, &w
) < 0)
318 res
= PyTuple_Pack(2, v
, w
);
324 PyDoc_STRVAR(coerce_doc
,
325 "coerce(x, y) -> (x1, y1)\n\
327 Return a tuple consisting of the two numeric arguments converted to\n\
328 a common type, using the same rules as used by arithmetic operations.\n\
329 If coercion is not possible, raise TypeError.");
332 builtin_compile(PyObject
*self
, PyObject
*args
)
338 int dont_inherit
= 0;
339 int supplied_flags
= 0;
341 PyObject
*result
, *cmd
, *tmp
= NULL
;
344 if (!PyArg_ParseTuple(args
, "Oss|ii:compile", &cmd
, &filename
,
345 &startstr
, &supplied_flags
, &dont_inherit
))
348 cf
.cf_flags
= supplied_flags
;
350 #ifdef Py_USING_UNICODE
351 if (PyUnicode_Check(cmd
)) {
352 tmp
= PyUnicode_AsUTF8String(cmd
);
356 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
359 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
361 if ((size_t)length
!= strlen(str
)) {
362 PyErr_SetString(PyExc_TypeError
,
363 "compile() expected string without null bytes");
367 if (strcmp(startstr
, "exec") == 0)
368 start
= Py_file_input
;
369 else if (strcmp(startstr
, "eval") == 0)
370 start
= Py_eval_input
;
371 else if (strcmp(startstr
, "single") == 0)
372 start
= Py_single_input
;
374 PyErr_SetString(PyExc_ValueError
,
375 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
380 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
))
382 PyErr_SetString(PyExc_ValueError
,
383 "compile(): unrecognised flags");
386 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
389 PyEval_MergeCompilerFlags(&cf
);
391 result
= Py_CompileStringFlags(str
, filename
, start
, &cf
);
396 PyDoc_STRVAR(compile_doc
,
397 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
399 Compile the source string (a Python module, statement or expression)\n\
400 into a code object that can be executed by the exec statement or eval().\n\
401 The filename will be used for run-time error messages.\n\
402 The mode must be 'exec' to compile a module, 'single' to compile a\n\
403 single (interactive) statement, or 'eval' to compile an expression.\n\
404 The flags argument, if present, controls which future statements influence\n\
405 the compilation of the code.\n\
406 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
407 the effects of any future statements in effect in the code calling\n\
408 compile; if absent or zero these statements do influence the compilation,\n\
409 in addition to any features explicitly specified.");
412 builtin_dir(PyObject
*self
, PyObject
*args
)
414 PyObject
*arg
= NULL
;
416 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
418 return PyObject_Dir(arg
);
421 PyDoc_STRVAR(dir_doc
,
422 "dir([object]) -> list of strings\n"
424 "Return an alphabetized list of names comprising (some of) the attributes\n"
425 "of the given object, and of attributes reachable from it:\n"
427 "No argument: the names in the current scope.\n"
428 "Module object: the module attributes.\n"
429 "Type or class object: its attributes, and recursively the attributes of\n"
431 "Otherwise: its attributes, its class's attributes, and recursively the\n"
432 " attributes of its class's base classes.");
435 builtin_divmod(PyObject
*self
, PyObject
*args
)
439 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
441 return PyNumber_Divmod(v
, w
);
444 PyDoc_STRVAR(divmod_doc
,
445 "divmod(x, y) -> (div, mod)\n\
447 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
451 builtin_eval(PyObject
*self
, PyObject
*args
)
453 PyObject
*cmd
, *result
, *tmp
= NULL
;
454 PyObject
*globals
= Py_None
, *locals
= Py_None
;
458 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
460 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
461 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
464 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
465 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
466 "globals must be a real dict; try eval(expr, {}, mapping)"
467 : "globals must be a dict");
470 if (globals
== Py_None
) {
471 globals
= PyEval_GetGlobals();
472 if (locals
== Py_None
)
473 locals
= PyEval_GetLocals();
475 else if (locals
== Py_None
)
478 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
479 if (PyDict_SetItemString(globals
, "__builtins__",
480 PyEval_GetBuiltins()) != 0)
484 if (PyCode_Check(cmd
)) {
485 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
486 PyErr_SetString(PyExc_TypeError
,
487 "code object passed to eval() may not contain free variables");
490 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
493 if (!PyString_Check(cmd
) &&
494 !PyUnicode_Check(cmd
)) {
495 PyErr_SetString(PyExc_TypeError
,
496 "eval() arg 1 must be a string or code object");
501 #ifdef Py_USING_UNICODE
502 if (PyUnicode_Check(cmd
)) {
503 tmp
= PyUnicode_AsUTF8String(cmd
);
507 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
510 if (PyString_AsStringAndSize(cmd
, &str
, NULL
))
512 while (*str
== ' ' || *str
== '\t')
515 (void)PyEval_MergeCompilerFlags(&cf
);
516 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
521 PyDoc_STRVAR(eval_doc
,
522 "eval(source[, globals[, locals]]) -> value\n\
524 Evaluate the source in the context of globals and locals.\n\
525 The source may be a string representing a Python expression\n\
526 or a code object as returned by compile().\n\
527 The globals must be a dictionary and locals can be any mappping,\n\
528 defaulting to the current globals and locals.\n\
529 If only globals is given, locals defaults to it.\n");
533 builtin_execfile(PyObject
*self
, PyObject
*args
)
536 PyObject
*globals
= Py_None
, *locals
= Py_None
;
542 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
544 &PyDict_Type
, &globals
,
547 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
548 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
551 if (globals
== Py_None
) {
552 globals
= PyEval_GetGlobals();
553 if (locals
== Py_None
)
554 locals
= PyEval_GetLocals();
556 else if (locals
== Py_None
)
558 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
559 if (PyDict_SetItemString(globals
, "__builtins__",
560 PyEval_GetBuiltins()) != 0)
565 /* Test for existence or directory. */
570 if ((d
= dirstat(filename
))!=nil
) {
572 werrstr("is a directory");
578 #elif defined(RISCOS)
579 if (object_exists(filename
)) {
585 #else /* standard Posix */
588 if (stat(filename
, &s
) == 0) {
589 if (S_ISDIR(s
.st_mode
))
590 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
602 Py_BEGIN_ALLOW_THREADS
603 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
612 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
616 if (PyEval_MergeCompilerFlags(&cf
))
617 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
620 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
625 PyDoc_STRVAR(execfile_doc
,
626 "execfile(filename[, globals[, locals]])\n\
628 Read and execute a Python script from a file.\n\
629 The globals and locals are dictionaries, defaulting to the current\n\
630 globals and locals. If only globals is given, locals defaults to it.");
634 builtin_getattr(PyObject
*self
, PyObject
*args
)
636 PyObject
*v
, *result
, *dflt
= NULL
;
639 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
641 #ifdef Py_USING_UNICODE
642 if (PyUnicode_Check(name
)) {
643 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
649 if (!PyString_Check(name
)) {
650 PyErr_SetString(PyExc_TypeError
,
651 "getattr(): attribute name must be string");
654 result
= PyObject_GetAttr(v
, name
);
655 if (result
== NULL
&& dflt
!= NULL
&&
656 PyErr_ExceptionMatches(PyExc_AttributeError
))
665 PyDoc_STRVAR(getattr_doc
,
666 "getattr(object, name[, default]) -> value\n\
668 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
669 When a default argument is given, it is returned when the attribute doesn't\n\
670 exist; without it, an exception is raised in that case.");
674 builtin_globals(PyObject
*self
)
678 d
= PyEval_GetGlobals();
683 PyDoc_STRVAR(globals_doc
,
684 "globals() -> dictionary\n\
686 Return the dictionary containing the current scope's global variables.");
690 builtin_hasattr(PyObject
*self
, PyObject
*args
)
695 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
697 #ifdef Py_USING_UNICODE
698 if (PyUnicode_Check(name
)) {
699 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
705 if (!PyString_Check(name
)) {
706 PyErr_SetString(PyExc_TypeError
,
707 "hasattr(): attribute name must be string");
710 v
= PyObject_GetAttr(v
, name
);
721 PyDoc_STRVAR(hasattr_doc
,
722 "hasattr(object, name) -> bool\n\
724 Return whether the object has an attribute with the given name.\n\
725 (This is done by calling getattr(object, name) and catching exceptions.)");
729 builtin_id(PyObject
*self
, PyObject
*v
)
731 return PyLong_FromVoidPtr(v
);
735 "id(object) -> integer\n\
737 Return the identity of an object. This is guaranteed to be unique among\n\
738 simultaneously existing objects. (Hint: it's the object's memory address.)");
742 builtin_map(PyObject
*self
, PyObject
*args
)
745 PyObject
*it
; /* the iterator object */
746 int saw_StopIteration
; /* bool: did the iterator end? */
749 PyObject
*func
, *result
;
750 sequence
*seqs
= NULL
, *sqp
;
754 n
= PyTuple_Size(args
);
756 PyErr_SetString(PyExc_TypeError
,
757 "map() requires at least two args");
761 func
= PyTuple_GetItem(args
, 0);
764 if (func
== Py_None
&& n
== 1) {
765 /* map(None, S) is the same as list(S). */
766 return PySequence_List(PyTuple_GetItem(args
, 1));
769 /* Get space for sequence descriptors. Must NULL out the iterator
770 * pointers so that jumping to Fail_2 later doesn't see trash.
772 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
776 for (i
= 0; i
< n
; ++i
) {
777 seqs
[i
].it
= (PyObject
*)NULL
;
778 seqs
[i
].saw_StopIteration
= 0;
781 /* Do a first pass to obtain iterators for the arguments, and set len
782 * to the largest of their lengths.
785 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
790 curseq
= PyTuple_GetItem(args
, i
+1);
791 sqp
->it
= PyObject_GetIter(curseq
);
792 if (sqp
->it
== NULL
) {
793 static char errmsg
[] =
794 "argument %d to map() must support iteration";
795 char errbuf
[sizeof(errmsg
) + 25];
796 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
797 PyErr_SetString(PyExc_TypeError
, errbuf
);
802 curlen
= PyObject_Size(curseq
);
805 curlen
= 8; /* arbitrary */
811 /* Get space for the result list. */
812 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
815 /* Iterate over the sequences until all have stopped. */
817 PyObject
*alist
, *item
=NULL
, *value
;
820 if (func
== Py_None
&& n
== 1)
822 else if ((alist
= PyTuple_New(n
)) == NULL
)
825 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
826 if (sqp
->saw_StopIteration
) {
831 item
= PyIter_Next(sqp
->it
);
835 if (PyErr_Occurred()) {
841 sqp
->saw_StopIteration
= 1;
845 PyTuple_SET_ITEM(alist
, j
, item
);
853 if (numactive
== 0) {
861 value
= PyEval_CallObject(func
, alist
);
867 int status
= PyList_Append(result
, value
);
872 else if (PyList_SetItem(result
, i
, value
) < 0)
876 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
887 for (i
= 0; i
< n
; ++i
)
888 Py_XDECREF(seqs
[i
].it
);
893 PyDoc_STRVAR(map_doc
,
894 "map(function, sequence[, sequence, ...]) -> list\n\
896 Return a list of the results of applying the function to the items of\n\
897 the argument sequence(s). If more than one sequence is given, the\n\
898 function is called with an argument list consisting of the corresponding\n\
899 item of each sequence, substituting None for missing values when not all\n\
900 sequences have the same length. If the function is None, return a list of\n\
901 the items of the sequence (or a list of tuples if more than one sequence).");
905 builtin_setattr(PyObject
*self
, PyObject
*args
)
911 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
913 if (PyObject_SetAttr(v
, name
, value
) != 0)
919 PyDoc_STRVAR(setattr_doc
,
920 "setattr(object, name, value)\n\
922 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
927 builtin_delattr(PyObject
*self
, PyObject
*args
)
932 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
934 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
940 PyDoc_STRVAR(delattr_doc
,
941 "delattr(object, name)\n\
943 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
948 builtin_hash(PyObject
*self
, PyObject
*v
)
952 x
= PyObject_Hash(v
);
955 return PyInt_FromLong(x
);
958 PyDoc_STRVAR(hash_doc
,
959 "hash(object) -> integer\n\
961 Return a hash value for the object. Two objects with the same value have\n\
962 the same hash value. The reverse is not necessarily true, but likely.");
966 builtin_hex(PyObject
*self
, PyObject
*v
)
971 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
972 nb
->nb_hex
== NULL
) {
973 PyErr_SetString(PyExc_TypeError
,
974 "hex() argument can't be converted to hex");
977 res
= (*nb
->nb_hex
)(v
);
978 if (res
&& !PyString_Check(res
)) {
979 PyErr_Format(PyExc_TypeError
,
980 "__hex__ returned non-string (type %.200s)",
981 res
->ob_type
->tp_name
);
988 PyDoc_STRVAR(hex_doc
,
989 "hex(number) -> string\n\
991 Return the hexadecimal representation of an integer or long integer.");
994 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
997 builtin_input(PyObject
*self
, PyObject
*args
)
1002 PyObject
*globals
, *locals
;
1005 line
= builtin_raw_input(self
, args
);
1008 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1010 while (*str
== ' ' || *str
== '\t')
1012 globals
= PyEval_GetGlobals();
1013 locals
= PyEval_GetLocals();
1014 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1015 if (PyDict_SetItemString(globals
, "__builtins__",
1016 PyEval_GetBuiltins()) != 0)
1020 PyEval_MergeCompilerFlags(&cf
);
1021 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1026 PyDoc_STRVAR(input_doc
,
1027 "input([prompt]) -> value\n\
1029 Equivalent to eval(raw_input(prompt)).");
1033 builtin_intern(PyObject
*self
, PyObject
*args
)
1036 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1038 if (!PyString_CheckExact(s
)) {
1039 PyErr_SetString(PyExc_TypeError
,
1040 "can't intern subclass of string");
1044 PyString_InternInPlace(&s
);
1048 PyDoc_STRVAR(intern_doc
,
1049 "intern(string) -> string\n\
1051 ``Intern'' the given string. This enters the string in the (global)\n\
1052 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1053 Return the string itself or the previously interned string object with the\n\
1058 builtin_iter(PyObject
*self
, PyObject
*args
)
1060 PyObject
*v
, *w
= NULL
;
1062 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1065 return PyObject_GetIter(v
);
1066 if (!PyCallable_Check(v
)) {
1067 PyErr_SetString(PyExc_TypeError
,
1068 "iter(v, w): v must be callable");
1071 return PyCallIter_New(v
, w
);
1074 PyDoc_STRVAR(iter_doc
,
1075 "iter(collection) -> iterator\n\
1076 iter(callable, sentinel) -> iterator\n\
1078 Get an iterator from an object. In the first form, the argument must\n\
1079 supply its own iterator, or be a sequence.\n\
1080 In the second form, the callable is called until it returns the sentinel.");
1084 builtin_len(PyObject
*self
, PyObject
*v
)
1088 res
= PyObject_Size(v
);
1089 if (res
< 0 && PyErr_Occurred())
1091 return PyInt_FromLong(res
);
1094 PyDoc_STRVAR(len_doc
,
1095 "len(object) -> integer\n\
1097 Return the number of items of a sequence or mapping.");
1101 builtin_locals(PyObject
*self
)
1105 d
= PyEval_GetLocals();
1110 PyDoc_STRVAR(locals_doc
,
1111 "locals() -> dictionary\n\
1113 Update and return a dictionary containing the current scope's local variables.");
1117 min_max(PyObject
*args
, int op
)
1119 const char *name
= op
== Py_LT
? "min" : "max";
1120 PyObject
*v
, *w
, *x
, *it
;
1122 if (PyTuple_Size(args
) > 1)
1124 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1127 it
= PyObject_GetIter(v
);
1131 w
= NULL
; /* the result */
1133 x
= PyIter_Next(it
);
1135 if (PyErr_Occurred()) {
1146 int cmp
= PyObject_RichCompareBool(x
, w
, op
);
1162 PyErr_Format(PyExc_ValueError
,
1163 "%s() arg is an empty sequence", name
);
1169 builtin_min(PyObject
*self
, PyObject
*v
)
1171 return min_max(v
, Py_LT
);
1174 PyDoc_STRVAR(min_doc
,
1175 "min(sequence) -> value\n\
1176 min(a, b, c, ...) -> value\n\
1178 With a single sequence argument, return its smallest item.\n\
1179 With two or more arguments, return the smallest argument.");
1183 builtin_max(PyObject
*self
, PyObject
*v
)
1185 return min_max(v
, Py_GT
);
1188 PyDoc_STRVAR(max_doc
,
1189 "max(sequence) -> value\n\
1190 max(a, b, c, ...) -> value\n\
1192 With a single sequence argument, return its largest item.\n\
1193 With two or more arguments, return the largest argument.");
1197 builtin_oct(PyObject
*self
, PyObject
*v
)
1199 PyNumberMethods
*nb
;
1202 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1203 nb
->nb_oct
== NULL
) {
1204 PyErr_SetString(PyExc_TypeError
,
1205 "oct() argument can't be converted to oct");
1208 res
= (*nb
->nb_oct
)(v
);
1209 if (res
&& !PyString_Check(res
)) {
1210 PyErr_Format(PyExc_TypeError
,
1211 "__oct__ returned non-string (type %.200s)",
1212 res
->ob_type
->tp_name
);
1219 PyDoc_STRVAR(oct_doc
,
1220 "oct(number) -> string\n\
1222 Return the octal representation of an integer or long integer.");
1226 builtin_ord(PyObject
*self
, PyObject
* obj
)
1231 if (PyString_Check(obj
)) {
1232 size
= PyString_GET_SIZE(obj
);
1234 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1235 return PyInt_FromLong(ord
);
1237 #ifdef Py_USING_UNICODE
1238 } else if (PyUnicode_Check(obj
)) {
1239 size
= PyUnicode_GET_SIZE(obj
);
1241 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1242 return PyInt_FromLong(ord
);
1246 PyErr_Format(PyExc_TypeError
,
1247 "ord() expected string of length 1, but " \
1248 "%.200s found", obj
->ob_type
->tp_name
);
1252 PyErr_Format(PyExc_TypeError
,
1253 "ord() expected a character, "
1254 "but string of length %d found",
1259 PyDoc_STRVAR(ord_doc
,
1260 "ord(c) -> integer\n\
1262 Return the integer ordinal of a one-character string.");
1266 builtin_pow(PyObject
*self
, PyObject
*args
)
1268 PyObject
*v
, *w
, *z
= Py_None
;
1270 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1272 return PyNumber_Power(v
, w
, z
);
1275 PyDoc_STRVAR(pow_doc
,
1276 "pow(x, y[, z]) -> number\n\
1278 With two arguments, equivalent to x**y. With three arguments,\n\
1279 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1283 /* Return number of items in range (lo, hi, step), when arguments are
1284 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1285 * & only if the true value is too large to fit in a signed long.
1286 * Arguments MUST return 1 with either PyInt_Check() or
1287 * PyLong_Check(). Return -1 when there is an error.
1290 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1292 /* -------------------------------------------------------------
1293 Algorithm is equal to that of get_len_of_range(), but it operates
1294 on PyObjects (which are assumed to be PyLong or PyInt objects).
1295 ---------------------------------------------------------------*/
1297 PyObject
*diff
= NULL
;
1298 PyObject
*one
= NULL
;
1299 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1300 /* holds sub-expression evaluations */
1302 /* if (lo >= hi), return length of 0. */
1303 if (PyObject_Compare(lo
, hi
) >= 0)
1306 if ((one
= PyLong_FromLong(1L)) == NULL
)
1309 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1312 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1315 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1318 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1321 n
= PyLong_AsLong(tmp3
);
1322 if (PyErr_Occurred()) { /* Check for Overflow */
1343 /* An extension of builtin_range() that handles the case when PyLong
1344 * arguments are given. */
1346 handle_range_longs(PyObject
*self
, PyObject
*args
)
1349 PyObject
*ihigh
= NULL
;
1350 PyObject
*istep
= NULL
;
1352 PyObject
*curnum
= NULL
;
1358 PyObject
*zero
= PyLong_FromLong(0);
1363 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1368 /* Figure out which way we were called, supply defaults, and be
1369 * sure to incref everything so that the decrefs at the end
1372 assert(ilow
!= NULL
);
1373 if (ihigh
== NULL
) {
1374 /* only 1 arg -- it's the upper limit */
1378 assert(ihigh
!= NULL
);
1381 /* ihigh correct now; do ilow */
1386 /* ilow and ihigh correct now; do istep */
1387 if (istep
== NULL
) {
1388 istep
= PyLong_FromLong(1L);
1396 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1397 PyErr_Format(PyExc_TypeError
,
1398 "range() integer start argument expected, got %s.",
1399 ilow
->ob_type
->tp_name
);
1403 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1404 PyErr_Format(PyExc_TypeError
,
1405 "range() integer end argument expected, got %s.",
1406 ihigh
->ob_type
->tp_name
);
1410 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1411 PyErr_Format(PyExc_TypeError
,
1412 "range() integer step argument expected, got %s.",
1413 istep
->ob_type
->tp_name
);
1417 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1419 if (cmp_result
== 0) {
1420 PyErr_SetString(PyExc_ValueError
,
1421 "range() step argument must not be zero");
1426 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1428 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1429 if (neg_istep
== NULL
)
1431 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1432 Py_DECREF(neg_istep
);
1436 if (bign
< 0 || (long)n
!= bign
) {
1437 PyErr_SetString(PyExc_OverflowError
,
1438 "range() result has too many items");
1449 for (i
= 0; i
< n
; i
++) {
1450 PyObject
*w
= PyNumber_Long(curnum
);
1455 PyList_SET_ITEM(v
, i
, w
);
1457 tmp_num
= PyNumber_Add(curnum
, istep
);
1458 if (tmp_num
== NULL
)
1481 /* Return number of items in range/xrange (lo, hi, step). step > 0
1482 * required. Return a value < 0 if & only if the true value is too
1483 * large to fit in a signed long.
1486 get_len_of_range(long lo
, long hi
, long step
)
1488 /* -------------------------------------------------------------
1489 If lo >= hi, the range is empty.
1490 Else if n values are in the range, the last one is
1491 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1492 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1493 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1494 the RHS is non-negative and so truncation is the same as the
1495 floor. Letting M be the largest positive long, the worst case
1496 for the RHS numerator is hi=M, lo=-M-1, and then
1497 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1498 precision to compute the RHS exactly.
1499 ---------------------------------------------------------------*/
1502 unsigned long uhi
= (unsigned long)hi
;
1503 unsigned long ulo
= (unsigned long)lo
;
1504 unsigned long diff
= uhi
- ulo
- 1;
1505 n
= (long)(diff
/ (unsigned long)step
+ 1);
1511 builtin_range(PyObject
*self
, PyObject
*args
)
1513 long ilow
= 0, ihigh
= 0, istep
= 1;
1519 if (PyTuple_Size(args
) <= 1) {
1520 if (!PyArg_ParseTuple(args
,
1521 "l;range() requires 1-3 int arguments",
1524 return handle_range_longs(self
, args
);
1528 if (!PyArg_ParseTuple(args
,
1529 "ll|l;range() requires 1-3 int arguments",
1530 &ilow
, &ihigh
, &istep
)) {
1532 return handle_range_longs(self
, args
);
1536 PyErr_SetString(PyExc_ValueError
,
1537 "range() step argument must not be zero");
1541 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1543 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1545 if (bign
< 0 || (long)n
!= bign
) {
1546 PyErr_SetString(PyExc_OverflowError
,
1547 "range() result has too many items");
1553 for (i
= 0; i
< n
; i
++) {
1554 PyObject
*w
= PyInt_FromLong(ilow
);
1559 PyList_SET_ITEM(v
, i
, w
);
1565 PyDoc_STRVAR(range_doc
,
1566 "range([start,] stop[, step]) -> list of integers\n\
1568 Return a list containing an arithmetic progression of integers.\n\
1569 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1570 When step is given, it specifies the increment (or decrement).\n\
1571 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1572 These are exactly the valid indices for a list of 4 elements.");
1576 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1579 PyObject
*fin
= PySys_GetObject("stdin");
1580 PyObject
*fout
= PySys_GetObject("stdout");
1582 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1586 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1590 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1593 if (PyFile_SoftSpace(fout
, 0)) {
1594 if (PyFile_WriteString(" ", fout
) != 0)
1597 if (PyFile_Check(fin
) && PyFile_Check(fout
)
1598 && isatty(fileno(PyFile_AsFile(fin
)))
1599 && isatty(fileno(PyFile_AsFile(fout
)))) {
1605 po
= PyObject_Str(v
);
1608 prompt
= PyString_AsString(po
);
1616 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
1620 if (!PyErr_Occurred())
1621 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1625 PyErr_SetNone(PyExc_EOFError
);
1628 else { /* strip trailing '\n' */
1629 size_t len
= strlen(s
);
1630 if (len
> INT_MAX
) {
1631 PyErr_SetString(PyExc_OverflowError
,
1632 "[raw_]input: input too long");
1636 result
= PyString_FromStringAndSize(s
,
1644 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
1647 return PyFile_GetLine(fin
, -1);
1650 PyDoc_STRVAR(raw_input_doc
,
1651 "raw_input([prompt]) -> string\n\
1653 Read a string from standard input. The trailing newline is stripped.\n\
1654 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1655 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1656 is printed without a trailing newline before reading.");
1660 builtin_reduce(PyObject
*self
, PyObject
*args
)
1662 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1664 if (!PyArg_UnpackTuple(args
, "reduce", 2, 3, &func
, &seq
, &result
))
1669 it
= PyObject_GetIter(seq
);
1671 PyErr_SetString(PyExc_TypeError
,
1672 "reduce() arg 2 must support iteration");
1677 if ((args
= PyTuple_New(2)) == NULL
)
1683 if (args
->ob_refcnt
> 1) {
1685 if ((args
= PyTuple_New(2)) == NULL
)
1689 op2
= PyIter_Next(it
);
1691 if (PyErr_Occurred())
1699 PyTuple_SetItem(args
, 0, result
);
1700 PyTuple_SetItem(args
, 1, op2
);
1701 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1709 PyErr_SetString(PyExc_TypeError
,
1710 "reduce() of empty sequence with no initial value");
1722 PyDoc_STRVAR(reduce_doc
,
1723 "reduce(function, sequence[, initial]) -> value\n\
1725 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1726 from left to right, so as to reduce the sequence to a single value.\n\
1727 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1728 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1729 of the sequence in the calculation, and serves as a default when the\n\
1730 sequence is empty.");
1734 builtin_reload(PyObject
*self
, PyObject
*v
)
1736 return PyImport_ReloadModule(v
);
1739 PyDoc_STRVAR(reload_doc
,
1740 "reload(module) -> module\n\
1742 Reload the module. The module must have been successfully imported before.");
1746 builtin_repr(PyObject
*self
, PyObject
*v
)
1748 return PyObject_Repr(v
);
1751 PyDoc_STRVAR(repr_doc
,
1752 "repr(object) -> string\n\
1754 Return the canonical string representation of the object.\n\
1755 For most object types, eval(repr(object)) == object.");
1759 builtin_round(PyObject
*self
, PyObject
*args
)
1766 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1784 return PyFloat_FromDouble(x
);
1787 PyDoc_STRVAR(round_doc
,
1788 "round(number[, ndigits]) -> floating point number\n\
1790 Round a number to a given precision in decimal digits (default 0 digits).\n\
1791 This always returns a floating point number. Precision may be negative.");
1794 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1796 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
1798 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
1802 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
1803 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
1807 newlist
= PySequence_List(seq
);
1808 if (newlist
== NULL
)
1811 callable
= PyObject_GetAttrString(newlist
, "sort");
1812 if (callable
== NULL
) {
1817 newargs
= PyTuple_GetSlice(args
, 1, 4);
1818 if (newargs
== NULL
) {
1820 Py_DECREF(callable
);
1824 v
= PyObject_Call(callable
, newargs
, kwds
);
1826 Py_DECREF(callable
);
1835 PyDoc_STRVAR(sorted_doc
,
1836 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
1839 builtin_vars(PyObject
*self
, PyObject
*args
)
1844 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
1847 d
= PyEval_GetLocals();
1849 if (!PyErr_Occurred())
1850 PyErr_SetString(PyExc_SystemError
,
1851 "vars(): no locals!?");
1857 d
= PyObject_GetAttrString(v
, "__dict__");
1859 PyErr_SetString(PyExc_TypeError
,
1860 "vars() argument must have __dict__ attribute");
1867 PyDoc_STRVAR(vars_doc
,
1868 "vars([object]) -> dictionary\n\
1870 Without arguments, equivalent to locals().\n\
1871 With an argument, equivalent to object.__dict__.");
1875 builtin_sum(PyObject
*self
, PyObject
*args
)
1878 PyObject
*result
= NULL
;
1879 PyObject
*temp
, *item
, *iter
;
1881 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
1884 iter
= PyObject_GetIter(seq
);
1888 if (result
== NULL
) {
1889 result
= PyInt_FromLong(0);
1890 if (result
== NULL
) {
1895 /* reject string values for 'start' parameter */
1896 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
1897 PyErr_SetString(PyExc_TypeError
,
1898 "sum() can't sum strings [use ''.join(seq) instead]");
1906 item
= PyIter_Next(iter
);
1908 /* error, or end-of-sequence */
1909 if (PyErr_Occurred()) {
1915 temp
= PyNumber_Add(result
, item
);
1926 PyDoc_STRVAR(sum_doc
,
1927 "sum(sequence, start=0) -> value\n\
1929 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
1930 of parameter 'start'. When the sequence is empty, returns start.");
1934 builtin_isinstance(PyObject
*self
, PyObject
*args
)
1940 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
1943 retval
= PyObject_IsInstance(inst
, cls
);
1946 return PyBool_FromLong(retval
);
1949 PyDoc_STRVAR(isinstance_doc
,
1950 "isinstance(object, class-or-type-or-tuple) -> bool\n\
1952 Return whether an object is an instance of a class or of a subclass thereof.\n\
1953 With a type as second argument, return whether that is the object's type.\n\
1954 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1955 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
1959 builtin_issubclass(PyObject
*self
, PyObject
*args
)
1965 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
1968 retval
= PyObject_IsSubclass(derived
, cls
);
1971 return PyBool_FromLong(retval
);
1974 PyDoc_STRVAR(issubclass_doc
,
1975 "issubclass(C, B) -> bool\n\
1977 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1978 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1979 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
1983 builtin_zip(PyObject
*self
, PyObject
*args
)
1986 const int itemsize
= PySequence_Length(args
);
1988 PyObject
*itlist
; /* tuple of iterators */
1989 int len
; /* guess at result length */
1992 return PyList_New(0);
1994 /* args must be a tuple */
1995 assert(PyTuple_Check(args
));
1997 /* Guess at result length: the shortest of the input lengths.
1998 If some argument refuses to say, we refuse to guess too, lest
1999 an argument like xrange(sys.maxint) lead us astray.*/
2000 len
= -1; /* unknown */
2001 for (i
= 0; i
< itemsize
; ++i
) {
2002 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2003 int thislen
= PyObject_Size(item
);
2009 else if (len
< 0 || thislen
< len
)
2013 /* allocate result list */
2015 len
= 10; /* arbitrary */
2016 if ((ret
= PyList_New(len
)) == NULL
)
2019 /* obtain iterators */
2020 itlist
= PyTuple_New(itemsize
);
2023 for (i
= 0; i
< itemsize
; ++i
) {
2024 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2025 PyObject
*it
= PyObject_GetIter(item
);
2027 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2028 PyErr_Format(PyExc_TypeError
,
2029 "zip argument #%d must support iteration",
2031 goto Fail_ret_itlist
;
2033 PyTuple_SET_ITEM(itlist
, i
, it
);
2036 /* build result into ret list */
2037 for (i
= 0; ; ++i
) {
2039 PyObject
*next
= PyTuple_New(itemsize
);
2041 goto Fail_ret_itlist
;
2043 for (j
= 0; j
< itemsize
; j
++) {
2044 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2045 PyObject
*item
= PyIter_Next(it
);
2047 if (PyErr_Occurred()) {
2055 PyTuple_SET_ITEM(next
, j
, item
);
2059 PyList_SET_ITEM(ret
, i
, next
);
2061 int status
= PyList_Append(ret
, next
);
2065 goto Fail_ret_itlist
;
2070 if (ret
!= NULL
&& i
< len
) {
2071 /* The list is too big. */
2072 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2085 PyDoc_STRVAR(zip_doc
,
2086 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2088 Return a list of tuples, where each tuple contains the i-th element\n\
2089 from each of the argument sequences. The returned list is truncated\n\
2090 in length to the length of the shortest argument sequence.");
2093 static PyMethodDef builtin_methods
[] = {
2094 {"__import__", builtin___import__
, METH_VARARGS
, import_doc
},
2095 {"abs", builtin_abs
, METH_O
, abs_doc
},
2096 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2097 {"callable", builtin_callable
, METH_O
, callable_doc
},
2098 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2099 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2100 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2101 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
2102 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2103 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2104 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2105 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2106 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2107 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2108 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2109 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2110 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2111 {"hash", builtin_hash
, METH_O
, hash_doc
},
2112 {"hex", builtin_hex
, METH_O
, hex_doc
},
2113 {"id", builtin_id
, METH_O
, id_doc
},
2114 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2115 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2116 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2117 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2118 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2119 {"len", builtin_len
, METH_O
, len_doc
},
2120 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2121 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2122 {"max", builtin_max
, METH_VARARGS
, max_doc
},
2123 {"min", builtin_min
, METH_VARARGS
, min_doc
},
2124 {"oct", builtin_oct
, METH_O
, oct_doc
},
2125 {"ord", builtin_ord
, METH_O
, ord_doc
},
2126 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2127 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2128 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2129 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2130 {"reload", builtin_reload
, METH_O
, reload_doc
},
2131 {"repr", builtin_repr
, METH_O
, repr_doc
},
2132 {"round", builtin_round
, METH_VARARGS
, round_doc
},
2133 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2134 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2135 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2136 #ifdef Py_USING_UNICODE
2137 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2139 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2140 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2144 PyDoc_STRVAR(builtin_doc
,
2145 "Built-in functions, exceptions, and other objects.\n\
2147 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2150 _PyBuiltin_Init(void)
2152 PyObject
*mod
, *dict
, *debug
;
2153 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2154 builtin_doc
, (PyObject
*)NULL
,
2155 PYTHON_API_VERSION
);
2158 dict
= PyModule_GetDict(mod
);
2160 #ifdef Py_TRACE_REFS
2161 /* __builtin__ exposes a number of statically allocated objects
2162 * that, before this code was added in 2.3, never showed up in
2163 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2164 * result, programs leaking references to None and False (etc)
2165 * couldn't be diagnosed by examining sys.getobjects(0).
2167 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2169 #define ADD_TO_ALL(OBJECT) (void)0
2172 #define SETBUILTIN(NAME, OBJECT) \
2173 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2177 SETBUILTIN("None", Py_None
);
2178 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2179 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2180 SETBUILTIN("False", Py_False
);
2181 SETBUILTIN("True", Py_True
);
2182 SETBUILTIN("basestring", &PyBaseString_Type
);
2183 SETBUILTIN("bool", &PyBool_Type
);
2184 SETBUILTIN("buffer", &PyBuffer_Type
);
2185 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2186 #ifndef WITHOUT_COMPLEX
2187 SETBUILTIN("complex", &PyComplex_Type
);
2189 SETBUILTIN("dict", &PyDict_Type
);
2190 SETBUILTIN("enumerate", &PyEnum_Type
);
2191 SETBUILTIN("float", &PyFloat_Type
);
2192 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2193 SETBUILTIN("property", &PyProperty_Type
);
2194 SETBUILTIN("int", &PyInt_Type
);
2195 SETBUILTIN("list", &PyList_Type
);
2196 SETBUILTIN("long", &PyLong_Type
);
2197 SETBUILTIN("object", &PyBaseObject_Type
);
2198 SETBUILTIN("reversed", &PyReversed_Type
);
2199 SETBUILTIN("set", &PySet_Type
);
2200 SETBUILTIN("slice", &PySlice_Type
);
2201 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2202 SETBUILTIN("str", &PyString_Type
);
2203 SETBUILTIN("super", &PySuper_Type
);
2204 SETBUILTIN("tuple", &PyTuple_Type
);
2205 SETBUILTIN("type", &PyType_Type
);
2206 SETBUILTIN("xrange", &PyRange_Type
);
2208 /* Note that open() is just an alias of file(). */
2209 SETBUILTIN("open", &PyFile_Type
);
2210 SETBUILTIN("file", &PyFile_Type
);
2211 #ifdef Py_USING_UNICODE
2212 SETBUILTIN("unicode", &PyUnicode_Type
);
2214 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2215 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2226 /* Helper for filter(): filter a tuple through a function */
2229 filtertuple(PyObject
*func
, PyObject
*tuple
)
2233 int len
= PyTuple_Size(tuple
);
2236 if (PyTuple_CheckExact(tuple
))
2239 tuple
= PyTuple_New(0);
2243 if ((result
= PyTuple_New(len
)) == NULL
)
2246 for (i
= j
= 0; i
< len
; ++i
) {
2247 PyObject
*item
, *good
;
2250 if (tuple
->ob_type
->tp_as_sequence
&&
2251 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2252 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2256 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2259 if (func
== Py_None
) {
2264 PyObject
*arg
= PyTuple_Pack(1, item
);
2269 good
= PyEval_CallObject(func
, arg
);
2276 ok
= PyObject_IsTrue(good
);
2279 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2286 if (_PyTuple_Resize(&result
, j
) < 0)
2297 /* Helper for filter(): filter a string through a function */
2300 filterstring(PyObject
*func
, PyObject
*strobj
)
2304 int len
= PyString_Size(strobj
);
2307 if (func
== Py_None
) {
2308 /* If it's a real string we can return the original,
2309 * as no character is ever false and __getitem__
2310 * does return this character. If it's a subclass
2311 * we must go through the __getitem__ loop */
2312 if (PyString_CheckExact(strobj
)) {
2317 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2320 for (i
= j
= 0; i
< len
; ++i
) {
2324 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2327 if (func
==Py_None
) {
2330 PyObject
*arg
, *good
;
2331 arg
= PyTuple_Pack(1, item
);
2336 good
= PyEval_CallObject(func
, arg
);
2342 ok
= PyObject_IsTrue(good
);
2347 if (!PyString_Check(item
)) {
2348 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2349 " __getitem__ returned different type");
2353 reslen
= PyString_GET_SIZE(item
);
2355 PyString_AS_STRING(result
)[j
++] =
2356 PyString_AS_STRING(item
)[0];
2358 /* do we need more space? */
2359 int need
= j
+ reslen
+ len
-i
-1;
2360 if (need
> outlen
) {
2361 /* overallocate, to avoid reallocations */
2364 if (_PyString_Resize(&result
, need
)) {
2371 PyString_AS_STRING(result
) + j
,
2372 PyString_AS_STRING(item
),
2382 _PyString_Resize(&result
, j
);
2391 #ifdef Py_USING_UNICODE
2392 /* Helper for filter(): filter a Unicode object through a function */
2395 filterunicode(PyObject
*func
, PyObject
*strobj
)
2399 int len
= PyUnicode_GetSize(strobj
);
2402 if (func
== Py_None
) {
2403 /* If it's a real string we can return the original,
2404 * as no character is ever false and __getitem__
2405 * does return this character. If it's a subclass
2406 * we must go through the __getitem__ loop */
2407 if (PyUnicode_CheckExact(strobj
)) {
2412 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2415 for (i
= j
= 0; i
< len
; ++i
) {
2416 PyObject
*item
, *arg
, *good
;
2419 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2422 if (func
== Py_None
) {
2425 arg
= PyTuple_Pack(1, item
);
2430 good
= PyEval_CallObject(func
, arg
);
2436 ok
= PyObject_IsTrue(good
);
2441 if (!PyUnicode_Check(item
)) {
2442 PyErr_SetString(PyExc_TypeError
,
2443 "can't filter unicode to unicode:"
2444 " __getitem__ returned different type");
2448 reslen
= PyUnicode_GET_SIZE(item
);
2450 PyUnicode_AS_UNICODE(result
)[j
++] =
2451 PyUnicode_AS_UNICODE(item
)[0];
2453 /* do we need more space? */
2454 int need
= j
+ reslen
+ len
- i
- 1;
2455 if (need
> outlen
) {
2457 to avoid reallocations */
2458 if (need
< 2 * outlen
)
2460 if (PyUnicode_Resize(
2461 &result
, need
) < 0) {
2467 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2468 PyUnicode_AS_UNICODE(item
),
2469 reslen
*sizeof(Py_UNICODE
));
2477 PyUnicode_Resize(&result
, j
);