2 /* Built-in functions */
17 #include "unixstuff.h"
20 /* The default encoding used by the platform file system APIs
21 Can remain NULL for all platforms that don't have such a concept
23 #if defined(MS_WIN32) && defined(HAVE_USABLE_WCHAR_T)
24 const char *Py_FileSystemDefaultEncoding
= "mbcs";
26 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
30 static PyObject
*filterstring(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 static char 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
);
65 static char abs_doc
[] =
66 "abs(number) -> number\n\
68 Return the absolute value of the argument.";
72 builtin_apply(PyObject
*self
, PyObject
*args
)
74 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
75 PyObject
*t
= NULL
, *retval
= NULL
;
77 if (!PyArg_ParseTuple(args
, "O|OO:apply", &func
, &alist
, &kwdict
))
80 if (!PyTuple_Check(alist
)) {
81 if (!PySequence_Check(alist
)) {
82 PyErr_Format(PyExc_TypeError
,
83 "apply() arg 2 expect sequence, found %s",
84 alist
->ob_type
->tp_name
);
87 t
= PySequence_Tuple(alist
);
93 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
94 PyErr_Format(PyExc_TypeError
,
95 "apply() arg 3 expected dictionary, found %s",
96 kwdict
->ob_type
->tp_name
);
99 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
105 static char apply_doc
[] =
106 "apply(object[, args[, kwargs]]) -> value\n\
108 Call a callable object with positional arguments taken from the tuple args,\n\
109 and keyword arguments taken from the optional dictionary kwargs.\n\
110 Note that classes are callable, as are instances with a __call__() method.";
114 builtin_buffer(PyObject
*self
, PyObject
*args
)
118 int size
= Py_END_OF_BUFFER
;
120 if ( !PyArg_ParseTuple(args
, "O|ii:buffer", &ob
, &offset
, &size
) )
122 return PyBuffer_FromObject(ob
, offset
, size
);
125 static char buffer_doc
[] =
126 "buffer(object [, offset[, size]]) -> object\n\
128 Create a new buffer object which references the given object.\n\
129 The buffer will reference a slice of the target object from the\n\
130 start of the object (or at the specified offset). The slice will\n\
131 extend to the end of the target object (or with the specified size).";
135 builtin_callable(PyObject
*self
, PyObject
*v
)
137 return PyInt_FromLong((long)PyCallable_Check(v
));
140 static char callable_doc
[] =
141 "callable(object) -> Boolean\n\
143 Return whether the object is callable (i.e., some kind of function).\n\
144 Note that classes are callable, as are instances with a __call__() method.";
148 builtin_filter(PyObject
*self
, PyObject
*args
)
150 PyObject
*func
, *seq
, *result
, *it
;
151 int len
; /* guess for result list size */
154 if (!PyArg_ParseTuple(args
, "OO:filter", &func
, &seq
))
157 /* Strings and tuples return a result of the same type. */
158 if (PyString_Check(seq
))
159 return filterstring(func
, seq
);
160 if (PyTuple_Check(seq
))
161 return filtertuple(func
, seq
);
164 it
= PyObject_GetIter(seq
);
168 /* Guess a result list size. */
169 len
= -1; /* unknown */
170 if (PySequence_Check(seq
) &&
171 seq
->ob_type
->tp_as_sequence
->sq_length
) {
172 len
= PySequence_Size(seq
);
177 len
= 8; /* arbitrary */
179 /* Get a result list. */
180 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
181 /* Eww - can modify the list in-place. */
186 result
= PyList_New(len
);
191 /* Build the result list. */
194 PyObject
*item
, *good
;
197 item
= PyIter_Next(it
);
199 if (PyErr_Occurred())
204 if (func
== Py_None
) {
209 PyObject
*arg
= Py_BuildValue("(O)", item
);
214 good
= PyEval_CallObject(func
, arg
);
221 ok
= PyObject_IsTrue(good
);
225 PyList_SET_ITEM(result
, j
, item
);
227 int status
= PyList_Append(result
, item
);
239 /* Cut back result list if len is too big. */
240 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
253 static char filter_doc
[] =
254 "filter(function, sequence) -> list\n\
256 Return a list containing those items of sequence for which function(item)\n\
257 is true. If function is None, return a list of items that are true.";
261 builtin_chr(PyObject
*self
, PyObject
*args
)
266 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
268 if (x
< 0 || x
>= 256) {
269 PyErr_SetString(PyExc_ValueError
,
270 "chr() arg not in range(256)");
274 return PyString_FromStringAndSize(s
, 1);
277 static char chr_doc
[] =
278 "chr(i) -> character\n\
280 Return a string of one character with ordinal i; 0 <= i < 256.";
283 #ifdef Py_USING_UNICODE
285 builtin_unichr(PyObject
*self
, PyObject
*args
)
290 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
293 #ifdef Py_UNICODE_WIDE
294 if (x
< 0 || x
> 0x10ffff) {
295 PyErr_SetString(PyExc_ValueError
,
296 "unichr() arg not in range(0x110000) "
297 "(wide Python build)");
301 if (x
< 0 || x
> 0xffff) {
302 PyErr_SetString(PyExc_ValueError
,
303 "unichr() arg not in range(0x10000) "
304 "(narrow Python build)");
310 /* UCS-2 character */
311 s
[0] = (Py_UNICODE
) x
;
312 return PyUnicode_FromUnicode(s
, 1);
315 #ifndef Py_UNICODE_WIDE
316 /* UCS-4 character. store as two surrogate characters */
318 s
[0] = 0xD800 + (Py_UNICODE
) (x
>> 10);
319 s
[1] = 0xDC00 + (Py_UNICODE
) (x
& 0x03FF);
320 return PyUnicode_FromUnicode(s
, 2);
322 s
[0] = (Py_UNICODE
)x
;
323 return PyUnicode_FromUnicode(s
, 1);
328 static char unichr_doc
[] =
329 "unichr(i) -> Unicode character\n\
331 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.";
336 builtin_cmp(PyObject
*self
, PyObject
*args
)
341 if (!PyArg_ParseTuple(args
, "OO:cmp", &a
, &b
))
343 if (PyObject_Cmp(a
, b
, &c
) < 0)
345 return PyInt_FromLong((long)c
);
348 static char cmp_doc
[] =
349 "cmp(x, y) -> integer\n\
351 Return negative if x<y, zero if x==y, positive if x>y.";
355 builtin_coerce(PyObject
*self
, PyObject
*args
)
360 if (!PyArg_ParseTuple(args
, "OO:coerce", &v
, &w
))
362 if (PyNumber_Coerce(&v
, &w
) < 0)
364 res
= Py_BuildValue("(OO)", v
, w
);
370 static char coerce_doc
[] =
371 "coerce(x, y) -> None or (x1, y1)\n\
373 When x and y can be coerced to values of the same type, return a tuple\n\
374 containing the coerced values. When they can't be coerced, return None.";
378 builtin_compile(PyObject
*self
, PyObject
*args
)
384 int dont_inherit
= 0;
385 int supplied_flags
= 0;
388 if (!PyArg_ParseTuple(args
, "sss|ii:compile", &str
, &filename
,
389 &startstr
, &supplied_flags
, &dont_inherit
))
392 if (strcmp(startstr
, "exec") == 0)
393 start
= Py_file_input
;
394 else if (strcmp(startstr
, "eval") == 0)
395 start
= Py_eval_input
;
396 else if (strcmp(startstr
, "single") == 0)
397 start
= Py_single_input
;
399 PyErr_SetString(PyExc_ValueError
,
400 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
404 if (supplied_flags
& ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
)) {
405 PyErr_SetString(PyExc_ValueError
,
406 "compile(): unrecognised flags");
409 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
411 cf
.cf_flags
= supplied_flags
;
413 PyEval_MergeCompilerFlags(&cf
);
415 return Py_CompileStringFlags(str
, filename
, start
, &cf
);
418 static char compile_doc
[] =
419 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
421 Compile the source string (a Python module, statement or expression)\n\
422 into a code object that can be executed by the exec statement or eval().\n\
423 The filename will be used for run-time error messages.\n\
424 The mode must be 'exec' to compile a module, 'single' to compile a\n\
425 single (interactive) statement, or 'eval' to compile an expression.\n\
426 The flags argument, if present, controls which future statements influence\n\
427 the compilation of the code.\n\
428 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
429 the effects of any future statements in effect in the code calling\n\
430 compile; if absent or zero these statements do influence the compilation,\n\
431 in addition to any features explicitly specified.";
434 builtin_dir(PyObject
*self
, PyObject
*args
)
436 PyObject
*arg
= NULL
;
438 if (!PyArg_ParseTuple(args
, "|O:dir", &arg
))
440 return PyObject_Dir(arg
);
443 static char dir_doc
[] =
444 "dir([object]) -> list of strings\n"
446 "Return an alphabetized list of names comprising (some of) the attributes\n"
447 "of the given object, and of attributes reachable from it:\n"
449 "No argument: the names in the current scope.\n"
450 "Module object: the module attributes.\n"
451 "Type or class object: its attributes, and recursively the attributes of\n"
453 "Otherwise: its attributes, its class's attributes, and recursively the\n"
454 " attributes of its class's base classes.";
457 builtin_divmod(PyObject
*self
, PyObject
*args
)
461 if (!PyArg_ParseTuple(args
, "OO:divmod", &v
, &w
))
463 return PyNumber_Divmod(v
, w
);
466 static char divmod_doc
[] =
467 "divmod(x, y) -> (div, mod)\n\
469 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
473 builtin_eval(PyObject
*self
, PyObject
*args
)
476 PyObject
*globals
= Py_None
, *locals
= Py_None
;
480 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
482 &PyDict_Type
, &globals
,
483 &PyDict_Type
, &locals
))
485 if (globals
== Py_None
) {
486 globals
= PyEval_GetGlobals();
487 if (locals
== Py_None
)
488 locals
= PyEval_GetLocals();
490 else if (locals
== Py_None
)
493 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
494 if (PyDict_SetItemString(globals
, "__builtins__",
495 PyEval_GetBuiltins()) != 0)
499 if (PyCode_Check(cmd
)) {
500 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
501 PyErr_SetString(PyExc_TypeError
,
502 "code object passed to eval() may not contain free variables");
505 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
508 if (!PyString_Check(cmd
) &&
509 !PyUnicode_Check(cmd
)) {
510 PyErr_SetString(PyExc_TypeError
,
511 "eval() arg 1 must be a string or code object");
514 if (PyString_AsStringAndSize(cmd
, &str
, NULL
))
516 while (*str
== ' ' || *str
== '\t')
520 (void)PyEval_MergeCompilerFlags(&cf
);
521 return PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
524 static char eval_doc
[] =
525 "eval(source[, globals[, locals]]) -> value\n\
527 Evaluate the source in the context of globals and locals.\n\
528 The source may be a string representing a Python expression\n\
529 or a code object as returned by compile().\n\
530 The globals and locals are dictionaries, defaulting to the current\n\
531 globals and locals. If only globals is given, locals defaults to it.";
535 builtin_execfile(PyObject
*self
, PyObject
*args
)
538 PyObject
*globals
= Py_None
, *locals
= Py_None
;
547 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
549 &PyDict_Type
, &globals
,
550 &PyDict_Type
, &locals
))
552 if (globals
== Py_None
) {
553 globals
= PyEval_GetGlobals();
554 if (locals
== Py_None
)
555 locals
= PyEval_GetLocals();
557 else if (locals
== Py_None
)
559 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
560 if (PyDict_SetItemString(globals
, "__builtins__",
561 PyEval_GetBuiltins()) != 0)
566 /* Test for existence or directory. */
568 if (!stat(filename
, &s
)) {
569 if (S_ISDIR(s
.st_mode
))
570 #if defined(PYOS_OS2) && defined(PYCC_VACPP)
579 if (object_exists(filename
)) {
588 Py_BEGIN_ALLOW_THREADS
589 fp
= fopen(filename
, "r");
598 PyErr_SetFromErrno(PyExc_IOError
);
602 if (PyEval_MergeCompilerFlags(&cf
))
603 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
606 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
611 static char execfile_doc
[] =
612 "execfile(filename[, globals[, locals]])\n\
614 Read and execute a Python script from a file.\n\
615 The globals and locals are dictionaries, defaulting to the current\n\
616 globals and locals. If only globals is given, locals defaults to it.";
620 builtin_getattr(PyObject
*self
, PyObject
*args
)
622 PyObject
*v
, *result
, *dflt
= NULL
;
625 if (!PyArg_ParseTuple(args
, "OO|O:getattr", &v
, &name
, &dflt
))
627 #ifdef Py_USING_UNICODE
628 if (PyUnicode_Check(name
)) {
629 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
635 if (!PyString_Check(name
)) {
636 PyErr_SetString(PyExc_TypeError
,
637 "attribute name must be string");
640 result
= PyObject_GetAttr(v
, name
);
641 if (result
== NULL
&& dflt
!= NULL
&&
642 PyErr_ExceptionMatches(PyExc_AttributeError
))
651 static char getattr_doc
[] =
652 "getattr(object, name[, default]) -> value\n\
654 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
655 When a default argument is given, it is returned when the attribute doesn't\n\
656 exist; without it, an exception is raised in that case.";
660 builtin_globals(PyObject
*self
)
664 d
= PyEval_GetGlobals();
669 static char globals_doc
[] =
670 "globals() -> dictionary\n\
672 Return the dictionary containing the current scope's global variables.";
676 builtin_hasattr(PyObject
*self
, PyObject
*args
)
681 if (!PyArg_ParseTuple(args
, "OO:hasattr", &v
, &name
))
683 #ifdef Py_USING_UNICODE
684 if (PyUnicode_Check(name
)) {
685 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
691 if (!PyString_Check(name
)) {
692 PyErr_SetString(PyExc_TypeError
,
693 "attribute name must be string");
696 v
= PyObject_GetAttr(v
, name
);
707 static char hasattr_doc
[] =
708 "hasattr(object, name) -> Boolean\n\
710 Return whether the object has an attribute with the given name.\n\
711 (This is done by calling getattr(object, name) and catching exceptions.)";
715 builtin_id(PyObject
*self
, PyObject
*v
)
717 return PyLong_FromVoidPtr(v
);
720 static char id_doc
[] =
721 "id(object) -> integer\n\
723 Return the identity of an object. This is guaranteed to be unique among\n\
724 simultaneously existing objects. (Hint: it's the object's memory address.)";
728 builtin_map(PyObject
*self
, PyObject
*args
)
731 PyObject
*it
; /* the iterator object */
732 int saw_StopIteration
; /* bool: did the iterator end? */
735 PyObject
*func
, *result
;
736 sequence
*seqs
= NULL
, *sqp
;
740 n
= PyTuple_Size(args
);
742 PyErr_SetString(PyExc_TypeError
,
743 "map() requires at least two args");
747 func
= PyTuple_GetItem(args
, 0);
750 if (func
== Py_None
&& n
== 1) {
751 /* map(None, S) is the same as list(S). */
752 return PySequence_List(PyTuple_GetItem(args
, 1));
755 /* Get space for sequence descriptors. Must NULL out the iterator
756 * pointers so that jumping to Fail_2 later doesn't see trash.
758 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
762 for (i
= 0; i
< n
; ++i
) {
763 seqs
[i
].it
= (PyObject
*)NULL
;
764 seqs
[i
].saw_StopIteration
= 0;
767 /* Do a first pass to obtain iterators for the arguments, and set len
768 * to the largest of their lengths.
771 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
776 curseq
= PyTuple_GetItem(args
, i
+1);
777 sqp
->it
= PyObject_GetIter(curseq
);
778 if (sqp
->it
== NULL
) {
779 static char errmsg
[] =
780 "argument %d to map() must support iteration";
781 char errbuf
[sizeof(errmsg
) + 25];
782 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
783 PyErr_SetString(PyExc_TypeError
, errbuf
);
788 curlen
= -1; /* unknown */
789 if (PySequence_Check(curseq
) &&
790 curseq
->ob_type
->tp_as_sequence
->sq_length
) {
791 curlen
= PySequence_Size(curseq
);
796 curlen
= 8; /* arbitrary */
801 /* Get space for the result list. */
802 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
805 /* Iterate over the sequences until all have stopped. */
807 PyObject
*alist
, *item
=NULL
, *value
;
810 if (func
== Py_None
&& n
== 1)
812 else if ((alist
= PyTuple_New(n
)) == NULL
)
815 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
816 if (sqp
->saw_StopIteration
) {
821 item
= PyIter_Next(sqp
->it
);
825 if (PyErr_Occurred()) {
831 sqp
->saw_StopIteration
= 1;
835 PyTuple_SET_ITEM(alist
, j
, item
);
843 if (numactive
== 0) {
851 value
= PyEval_CallObject(func
, alist
);
857 int status
= PyList_Append(result
, value
);
862 else if (PyList_SetItem(result
, i
, value
) < 0)
866 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
877 for (i
= 0; i
< n
; ++i
)
878 Py_XDECREF(seqs
[i
].it
);
883 static char map_doc
[] =
884 "map(function, sequence[, sequence, ...]) -> list\n\
886 Return a list of the results of applying the function to the items of\n\
887 the argument sequence(s). If more than one sequence is given, the\n\
888 function is called with an argument list consisting of the corresponding\n\
889 item of each sequence, substituting None for missing values when not all\n\
890 sequences have the same length. If the function is None, return a list of\n\
891 the items of the sequence (or a list of tuples if more than one sequence).";
895 builtin_setattr(PyObject
*self
, PyObject
*args
)
901 if (!PyArg_ParseTuple(args
, "OOO:setattr", &v
, &name
, &value
))
903 if (PyObject_SetAttr(v
, name
, value
) != 0)
909 static char setattr_doc
[] =
910 "setattr(object, name, value)\n\
912 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
917 builtin_delattr(PyObject
*self
, PyObject
*args
)
922 if (!PyArg_ParseTuple(args
, "OO:delattr", &v
, &name
))
924 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
930 static char delattr_doc
[] =
931 "delattr(object, name)\n\
933 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
938 builtin_hash(PyObject
*self
, PyObject
*v
)
942 x
= PyObject_Hash(v
);
945 return PyInt_FromLong(x
);
948 static char hash_doc
[] =
949 "hash(object) -> integer\n\
951 Return a hash value for the object. Two objects with the same value have\n\
952 the same hash value. The reverse is not necessarily true, but likely.";
956 builtin_hex(PyObject
*self
, PyObject
*v
)
960 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
961 nb
->nb_hex
== NULL
) {
962 PyErr_SetString(PyExc_TypeError
,
963 "hex() argument can't be converted to hex");
966 return (*nb
->nb_hex
)(v
);
969 static char hex_doc
[] =
970 "hex(number) -> string\n\
972 Return the hexadecimal representation of an integer or long integer.";
975 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
978 builtin_input(PyObject
*self
, PyObject
*args
)
983 PyObject
*globals
, *locals
;
985 line
= builtin_raw_input(self
, args
);
988 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
990 while (*str
== ' ' || *str
== '\t')
992 globals
= PyEval_GetGlobals();
993 locals
= PyEval_GetLocals();
994 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
995 if (PyDict_SetItemString(globals
, "__builtins__",
996 PyEval_GetBuiltins()) != 0)
999 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
1004 static char input_doc
[] =
1005 "input([prompt]) -> value\n\
1007 Equivalent to eval(raw_input(prompt)).";
1011 builtin_intern(PyObject
*self
, PyObject
*args
)
1014 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1017 PyString_InternInPlace(&s
);
1021 static char intern_doc
[] =
1022 "intern(string) -> string\n\
1024 ``Intern'' the given string. This enters the string in the (global)\n\
1025 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1026 Return the string itself or the previously interned string object with the\n\
1031 builtin_iter(PyObject
*self
, PyObject
*args
)
1033 PyObject
*v
, *w
= NULL
;
1035 if (!PyArg_ParseTuple(args
, "O|O:iter", &v
, &w
))
1038 return PyObject_GetIter(v
);
1039 if (!PyCallable_Check(v
)) {
1040 PyErr_SetString(PyExc_TypeError
,
1041 "iter(v, w): v must be callable");
1044 return PyCallIter_New(v
, w
);
1047 static char iter_doc
[] =
1048 "iter(collection) -> iterator\n\
1049 iter(callable, sentinel) -> iterator\n\
1051 Get an iterator from an object. In the first form, the argument must\n\
1052 supply its own iterator, or be a sequence.\n\
1053 In the second form, the callable is called until it returns the sentinel.";
1057 builtin_len(PyObject
*self
, PyObject
*v
)
1061 res
= PyObject_Size(v
);
1062 if (res
< 0 && PyErr_Occurred())
1064 return PyInt_FromLong(res
);
1067 static char len_doc
[] =
1068 "len(object) -> integer\n\
1070 Return the number of items of a sequence or mapping.";
1074 builtin_slice(PyObject
*self
, PyObject
*args
)
1076 PyObject
*start
, *stop
, *step
;
1078 start
= stop
= step
= NULL
;
1080 if (!PyArg_ParseTuple(args
, "O|OO:slice", &start
, &stop
, &step
))
1083 /* This swapping of stop and start is to maintain similarity with
1089 return PySlice_New(start
, stop
, step
);
1092 static char slice_doc
[] =
1093 "slice([start,] stop[, step]) -> slice object\n\
1095 Create a slice object. This is used for slicing by the Numeric extensions.";
1099 builtin_locals(PyObject
*self
)
1103 d
= PyEval_GetLocals();
1108 static char locals_doc
[] =
1109 "locals() -> dictionary\n\
1111 Return the dictionary containing the current scope's local variables.";
1115 min_max(PyObject
*args
, int op
)
1117 PyObject
*v
, *w
, *x
, *it
;
1119 if (PyTuple_Size(args
) > 1)
1121 else if (!PyArg_ParseTuple(args
, "O:min/max", &v
))
1124 it
= PyObject_GetIter(v
);
1128 w
= NULL
; /* the result */
1130 x
= PyIter_Next(it
);
1132 if (PyErr_Occurred()) {
1143 int cmp
= PyObject_RichCompareBool(x
, w
, op
);
1159 PyErr_SetString(PyExc_ValueError
,
1160 "min() or max() arg is an empty sequence");
1166 builtin_min(PyObject
*self
, PyObject
*v
)
1168 return min_max(v
, Py_LT
);
1171 static char min_doc
[] =
1172 "min(sequence) -> value\n\
1173 min(a, b, c, ...) -> value\n\
1175 With a single sequence argument, return its smallest item.\n\
1176 With two or more arguments, return the smallest argument.";
1180 builtin_max(PyObject
*self
, PyObject
*v
)
1182 return min_max(v
, Py_GT
);
1185 static char max_doc
[] =
1186 "max(sequence) -> value\n\
1187 max(a, b, c, ...) -> value\n\
1189 With a single sequence argument, return its largest item.\n\
1190 With two or more arguments, return the largest argument.";
1194 builtin_oct(PyObject
*self
, PyObject
*v
)
1196 PyNumberMethods
*nb
;
1198 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1199 nb
->nb_oct
== NULL
) {
1200 PyErr_SetString(PyExc_TypeError
,
1201 "oct() argument can't be converted to oct");
1204 return (*nb
->nb_oct
)(v
);
1207 static char oct_doc
[] =
1208 "oct(number) -> string\n\
1210 Return the octal representation of an integer or long integer.";
1214 builtin_ord(PyObject
*self
, PyObject
* obj
)
1219 if (PyString_Check(obj
)) {
1220 size
= PyString_GET_SIZE(obj
);
1222 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1223 return PyInt_FromLong(ord
);
1225 #ifdef Py_USING_UNICODE
1226 } else if (PyUnicode_Check(obj
)) {
1227 size
= PyUnicode_GET_SIZE(obj
);
1229 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1230 return PyInt_FromLong(ord
);
1234 PyErr_Format(PyExc_TypeError
,
1235 "ord() expected string of length 1, but " \
1236 "%.200s found", obj
->ob_type
->tp_name
);
1240 PyErr_Format(PyExc_TypeError
,
1241 "ord() expected a character, "
1242 "but string of length %d found",
1247 static char ord_doc
[] =
1248 "ord(c) -> integer\n\
1250 Return the integer ordinal of a one-character string.";
1254 builtin_pow(PyObject
*self
, PyObject
*args
)
1256 PyObject
*v
, *w
, *z
= Py_None
;
1258 if (!PyArg_ParseTuple(args
, "OO|O:pow", &v
, &w
, &z
))
1260 return PyNumber_Power(v
, w
, z
);
1263 static char pow_doc
[] =
1264 "pow(x, y[, z]) -> number\n\
1266 With two arguments, equivalent to x**y. With three arguments,\n\
1267 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1270 /* Return number of items in range/xrange (lo, hi, step). step > 0
1271 * required. Return a value < 0 if & only if the true value is too
1272 * large to fit in a signed long.
1275 get_len_of_range(long lo
, long hi
, long step
)
1277 /* -------------------------------------------------------------
1278 If lo >= hi, the range is empty.
1279 Else if n values are in the range, the last one is
1280 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1281 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1282 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1283 the RHS is non-negative and so truncation is the same as the
1284 floor. Letting M be the largest positive long, the worst case
1285 for the RHS numerator is hi=M, lo=-M-1, and then
1286 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1287 precision to compute the RHS exactly.
1288 ---------------------------------------------------------------*/
1291 unsigned long uhi
= (unsigned long)hi
;
1292 unsigned long ulo
= (unsigned long)lo
;
1293 unsigned long diff
= uhi
- ulo
- 1;
1294 n
= (long)(diff
/ (unsigned long)step
+ 1);
1300 builtin_range(PyObject
*self
, PyObject
*args
)
1302 long ilow
= 0, ihigh
= 0, istep
= 1;
1308 if (PyTuple_Size(args
) <= 1) {
1309 if (!PyArg_ParseTuple(args
,
1310 "l;range() requires 1-3 int arguments",
1315 if (!PyArg_ParseTuple(args
,
1316 "ll|l;range() requires 1-3 int arguments",
1317 &ilow
, &ihigh
, &istep
))
1321 PyErr_SetString(PyExc_ValueError
, "range() arg 3 must not be zero");
1325 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1327 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1329 if (bign
< 0 || (long)n
!= bign
) {
1330 PyErr_SetString(PyExc_OverflowError
,
1331 "range() result has too many items");
1337 for (i
= 0; i
< n
; i
++) {
1338 PyObject
*w
= PyInt_FromLong(ilow
);
1343 PyList_SET_ITEM(v
, i
, w
);
1349 static char range_doc
[] =
1350 "range([start,] stop[, step]) -> list of integers\n\
1352 Return a list containing an arithmetic progression of integers.\n\
1353 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1354 When step is given, it specifies the increment (or decrement).\n\
1355 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1356 These are exactly the valid indices for a list of 4 elements.";
1360 builtin_xrange(PyObject
*self
, PyObject
*args
)
1362 long ilow
= 0, ihigh
= 0, istep
= 1;
1365 if (PyTuple_Size(args
) <= 1) {
1366 if (!PyArg_ParseTuple(args
,
1367 "l;xrange() requires 1-3 int arguments",
1372 if (!PyArg_ParseTuple(args
,
1373 "ll|l;xrange() requires 1-3 int arguments",
1374 &ilow
, &ihigh
, &istep
))
1378 PyErr_SetString(PyExc_ValueError
, "xrange() arg 3 must not be zero");
1382 n
= get_len_of_range(ilow
, ihigh
, istep
);
1384 n
= get_len_of_range(ihigh
, ilow
, -istep
);
1386 PyErr_SetString(PyExc_OverflowError
,
1387 "xrange() result has too many items");
1390 return PyRange_New(ilow
, n
, istep
, 1);
1393 static char xrange_doc
[] =
1394 "xrange([start,] stop[, step]) -> xrange object\n\
1396 Like range(), but instead of returning a list, returns an object that\n\
1397 generates the numbers in the range on demand. This is slightly slower\n\
1398 than range() but more memory efficient.";
1402 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1407 if (!PyArg_ParseTuple(args
, "|O:[raw_]input", &v
))
1409 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin
&&
1410 PyFile_AsFile(PySys_GetObject("stdout")) == stdout
&&
1411 isatty(fileno(stdin
)) && isatty(fileno(stdout
))) {
1417 po
= PyObject_Str(v
);
1420 prompt
= PyString_AsString(po
);
1428 s
= PyOS_Readline(prompt
);
1431 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1435 PyErr_SetNone(PyExc_EOFError
);
1438 else { /* strip trailing '\n' */
1439 size_t len
= strlen(s
);
1440 if (len
> INT_MAX
) {
1441 PyErr_SetString(PyExc_OverflowError
, "input too long");
1445 result
= PyString_FromStringAndSize(s
, (int)(len
-1));
1452 f
= PySys_GetObject("stdout");
1454 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
1457 if (Py_FlushLine() != 0 ||
1458 PyFile_WriteObject(v
, f
, Py_PRINT_RAW
) != 0)
1461 f
= PySys_GetObject("stdin");
1463 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdin");
1466 return PyFile_GetLine(f
, -1);
1469 static char raw_input_doc
[] =
1470 "raw_input([prompt]) -> string\n\
1472 Read a string from standard input. The trailing newline is stripped.\n\
1473 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1474 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1475 is printed without a trailing newline before reading.";
1479 builtin_reduce(PyObject
*self
, PyObject
*args
)
1481 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1483 if (!PyArg_ParseTuple(args
, "OO|O:reduce", &func
, &seq
, &result
))
1488 it
= PyObject_GetIter(seq
);
1490 PyErr_SetString(PyExc_TypeError
,
1491 "reduce() arg 2 must support iteration");
1496 if ((args
= PyTuple_New(2)) == NULL
)
1502 if (args
->ob_refcnt
> 1) {
1504 if ((args
= PyTuple_New(2)) == NULL
)
1508 op2
= PyIter_Next(it
);
1510 if (PyErr_Occurred())
1518 PyTuple_SetItem(args
, 0, result
);
1519 PyTuple_SetItem(args
, 1, op2
);
1520 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1528 PyErr_SetString(PyExc_TypeError
,
1529 "reduce() of empty sequence with no initial value");
1541 static char reduce_doc
[] =
1542 "reduce(function, sequence[, initial]) -> value\n\
1544 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1545 from left to right, so as to reduce the sequence to a single value.\n\
1546 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1547 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1548 of the sequence in the calculation, and serves as a default when the\n\
1549 sequence is empty.";
1553 builtin_reload(PyObject
*self
, PyObject
*v
)
1555 return PyImport_ReloadModule(v
);
1558 static char reload_doc
[] =
1559 "reload(module) -> module\n\
1561 Reload the module. The module must have been successfully imported before.";
1565 builtin_repr(PyObject
*self
, PyObject
*v
)
1567 return PyObject_Repr(v
);
1570 static char repr_doc
[] =
1571 "repr(object) -> string\n\
1573 Return the canonical string representation of the object.\n\
1574 For most object types, eval(repr(object)) == object.";
1578 builtin_round(PyObject
*self
, PyObject
*args
)
1585 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1603 return PyFloat_FromDouble(x
);
1606 static char round_doc
[] =
1607 "round(number[, ndigits]) -> floating point number\n\
1609 Round a number to a given precision in decimal digits (default 0 digits).\n\
1610 This always returns a floating point number. Precision may be negative.";
1614 builtin_vars(PyObject
*self
, PyObject
*args
)
1619 if (!PyArg_ParseTuple(args
, "|O:vars", &v
))
1622 d
= PyEval_GetLocals();
1624 if (!PyErr_Occurred())
1625 PyErr_SetString(PyExc_SystemError
,
1632 d
= PyObject_GetAttrString(v
, "__dict__");
1634 PyErr_SetString(PyExc_TypeError
,
1635 "vars() argument must have __dict__ attribute");
1642 static char vars_doc
[] =
1643 "vars([object]) -> dictionary\n\
1645 Without arguments, equivalent to locals().\n\
1646 With an argument, equivalent to object.__dict__.";
1649 builtin_isinstance(PyObject
*self
, PyObject
*args
)
1655 if (!PyArg_ParseTuple(args
, "OO:isinstance", &inst
, &cls
))
1658 retval
= PyObject_IsInstance(inst
, cls
);
1661 return PyInt_FromLong(retval
);
1664 static char isinstance_doc
[] =
1665 "isinstance(object, class-or-type-or-tuple) -> Boolean\n\
1667 Return whether an object is an instance of a class or of a subclass thereof.\n\
1668 With a type as second argument, return whether that is the object's type.\n\
1669 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1670 isinstance(x, A) or isinstance(x, B) or ... (etc.).";
1674 builtin_issubclass(PyObject
*self
, PyObject
*args
)
1680 if (!PyArg_ParseTuple(args
, "OO:issubclass", &derived
, &cls
))
1683 retval
= PyObject_IsSubclass(derived
, cls
);
1686 return PyInt_FromLong(retval
);
1689 static char issubclass_doc
[] =
1690 "issubclass(C, B) -> Boolean\n\
1692 Return whether class C is a subclass (i.e., a derived class) of class B.";
1696 builtin_zip(PyObject
*self
, PyObject
*args
)
1699 int itemsize
= PySequence_Length(args
);
1701 PyObject
*itlist
; /* tuple of iterators */
1704 PyErr_SetString(PyExc_TypeError
,
1705 "zip() requires at least one sequence");
1708 /* args must be a tuple */
1709 assert(PyTuple_Check(args
));
1711 /* allocate result list */
1712 if ((ret
= PyList_New(0)) == NULL
)
1715 /* obtain iterators */
1716 itlist
= PyTuple_New(itemsize
);
1719 for (i
= 0; i
< itemsize
; ++i
) {
1720 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
1721 PyObject
*it
= PyObject_GetIter(item
);
1723 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1724 PyErr_Format(PyExc_TypeError
,
1725 "zip argument #%d must support iteration",
1727 goto Fail_ret_itlist
;
1729 PyTuple_SET_ITEM(itlist
, i
, it
);
1732 /* build result into ret list */
1735 PyObject
*next
= PyTuple_New(itemsize
);
1737 goto Fail_ret_itlist
;
1739 for (i
= 0; i
< itemsize
; i
++) {
1740 PyObject
*it
= PyTuple_GET_ITEM(itlist
, i
);
1741 PyObject
*item
= PyIter_Next(it
);
1743 if (PyErr_Occurred()) {
1751 PyTuple_SET_ITEM(next
, i
, item
);
1754 status
= PyList_Append(ret
, next
);
1757 goto Fail_ret_itlist
;
1768 static char zip_doc
[] =
1769 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1771 Return a list of tuples, where each tuple contains the i-th element\n\
1772 from each of the argument sequences. The returned list is truncated\n\
1773 in length to the length of the shortest argument sequence.";
1776 static PyMethodDef builtin_methods
[] = {
1777 {"__import__", builtin___import__
, METH_VARARGS
, import_doc
},
1778 {"abs", builtin_abs
, METH_O
, abs_doc
},
1779 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
1780 {"buffer", builtin_buffer
, METH_VARARGS
, buffer_doc
},
1781 {"callable", builtin_callable
, METH_O
, callable_doc
},
1782 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
1783 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
1784 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
1785 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
1786 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
1787 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
1788 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
1789 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
1790 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
1791 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
1792 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
1793 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
1794 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
1795 {"hash", builtin_hash
, METH_O
, hash_doc
},
1796 {"hex", builtin_hex
, METH_O
, hex_doc
},
1797 {"id", builtin_id
, METH_O
, id_doc
},
1798 {"input", builtin_input
, METH_VARARGS
, input_doc
},
1799 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
1800 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
1801 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
1802 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
1803 {"len", builtin_len
, METH_O
, len_doc
},
1804 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
1805 {"map", builtin_map
, METH_VARARGS
, map_doc
},
1806 {"max", builtin_max
, METH_VARARGS
, max_doc
},
1807 {"min", builtin_min
, METH_VARARGS
, min_doc
},
1808 {"oct", builtin_oct
, METH_O
, oct_doc
},
1809 {"ord", builtin_ord
, METH_O
, ord_doc
},
1810 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
1811 {"range", builtin_range
, METH_VARARGS
, range_doc
},
1812 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
1813 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
1814 {"reload", builtin_reload
, METH_O
, reload_doc
},
1815 {"repr", builtin_repr
, METH_O
, repr_doc
},
1816 {"round", builtin_round
, METH_VARARGS
, round_doc
},
1817 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
1818 {"slice", builtin_slice
, METH_VARARGS
, slice_doc
},
1819 #ifdef Py_USING_UNICODE
1820 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
1822 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
1823 {"xrange", builtin_xrange
, METH_VARARGS
, xrange_doc
},
1824 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
1828 static char builtin_doc
[] =
1829 "Built-in functions, exceptions, and other objects.\n\
1831 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
1834 _PyBuiltin_Init(void)
1836 PyObject
*mod
, *dict
, *debug
;
1837 mod
= Py_InitModule4("__builtin__", builtin_methods
,
1838 builtin_doc
, (PyObject
*)NULL
,
1839 PYTHON_API_VERSION
);
1842 dict
= PyModule_GetDict(mod
);
1844 #define SETBUILTIN(NAME, OBJECT) \
1845 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1848 SETBUILTIN("None", Py_None
);
1849 SETBUILTIN("Ellipsis", Py_Ellipsis
);
1850 SETBUILTIN("NotImplemented", Py_NotImplemented
);
1851 SETBUILTIN("classmethod", &PyClassMethod_Type
);
1852 #ifndef WITHOUT_COMPLEX
1853 SETBUILTIN("complex", &PyComplex_Type
);
1855 SETBUILTIN("dict", &PyDict_Type
);
1856 SETBUILTIN("float", &PyFloat_Type
);
1857 SETBUILTIN("property", &PyProperty_Type
);
1858 SETBUILTIN("int", &PyInt_Type
);
1859 SETBUILTIN("list", &PyList_Type
);
1860 SETBUILTIN("long", &PyLong_Type
);
1861 SETBUILTIN("object", &PyBaseObject_Type
);
1862 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
1863 SETBUILTIN("str", &PyString_Type
);
1864 SETBUILTIN("super", &PySuper_Type
);
1865 SETBUILTIN("tuple", &PyTuple_Type
);
1866 SETBUILTIN("type", &PyType_Type
);
1868 /* Note that open() is just an alias of file(). */
1869 SETBUILTIN("open", &PyFile_Type
);
1870 SETBUILTIN("file", &PyFile_Type
);
1871 #ifdef Py_USING_UNICODE
1872 SETBUILTIN("unicode", &PyUnicode_Type
);
1874 debug
= PyInt_FromLong(Py_OptimizeFlag
== 0);
1875 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
1885 /* Helper for filter(): filter a tuple through a function */
1888 filtertuple(PyObject
*func
, PyObject
*tuple
)
1892 int len
= PyTuple_Size(tuple
);
1899 if ((result
= PyTuple_New(len
)) == NULL
)
1902 for (i
= j
= 0; i
< len
; ++i
) {
1903 PyObject
*item
, *good
;
1906 if ((item
= PyTuple_GetItem(tuple
, i
)) == NULL
)
1908 if (func
== Py_None
) {
1913 PyObject
*arg
= Py_BuildValue("(O)", item
);
1916 good
= PyEval_CallObject(func
, arg
);
1921 ok
= PyObject_IsTrue(good
);
1925 if (PyTuple_SetItem(result
, j
++, item
) < 0)
1930 if (_PyTuple_Resize(&result
, j
) < 0)
1941 /* Helper for filter(): filter a string through a function */
1944 filterstring(PyObject
*func
, PyObject
*strobj
)
1948 int len
= PyString_Size(strobj
);
1950 if (func
== Py_None
) {
1951 /* No character is ever false -- share input string */
1955 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
1958 for (i
= j
= 0; i
< len
; ++i
) {
1959 PyObject
*item
, *arg
, *good
;
1962 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
1965 arg
= Py_BuildValue("(O)", item
);
1970 good
= PyEval_CallObject(func
, arg
);
1976 ok
= PyObject_IsTrue(good
);
1979 PyString_AS_STRING((PyStringObject
*)result
)[j
++] =
1980 PyString_AS_STRING((PyStringObject
*)item
)[0];
1984 if (j
< len
&& _PyString_Resize(&result
, j
) < 0)