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_WIN32) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding
= "mbcs";
22 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
26 static PyObject
*filterstring(PyObject
*, PyObject
*);
27 static PyObject
*filtertuple (PyObject
*, PyObject
*);
30 builtin___import__(PyObject
*self
, PyObject
*args
)
33 PyObject
*globals
= NULL
;
34 PyObject
*locals
= NULL
;
35 PyObject
*fromlist
= NULL
;
37 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
38 &name
, &globals
, &locals
, &fromlist
))
40 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
43 PyDoc_STRVAR(import_doc
,
44 "__import__(name, globals, locals, fromlist) -> module\n\
46 Import a module. The globals are only used to determine the context;\n\
47 they are not modified. The locals are currently unused. The fromlist\n\
48 should be a list of names to emulate ``from name import ...'', or an\n\
49 empty list to emulate ``import name''.\n\
50 When importing a module from a package, note that __import__('A.B', ...)\n\
51 returns package A when fromlist is empty, but its submodule B when\n\
52 fromlist is not empty.");
56 builtin_abs(PyObject
*self
, PyObject
*v
)
58 return PyNumber_Absolute(v
);
62 "abs(number) -> number\n\
64 Return the absolute value of the argument.");
68 builtin_apply(PyObject
*self
, PyObject
*args
)
70 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
71 PyObject
*t
= NULL
, *retval
= NULL
;
73 if (!PyArg_ParseTuple(args
, "O|OO:apply", &func
, &alist
, &kwdict
))
76 if (!PyTuple_Check(alist
)) {
77 if (!PySequence_Check(alist
)) {
78 PyErr_Format(PyExc_TypeError
,
79 "apply() arg 2 expect sequence, found %s",
80 alist
->ob_type
->tp_name
);
83 t
= PySequence_Tuple(alist
);
89 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
90 PyErr_Format(PyExc_TypeError
,
91 "apply() arg 3 expected dictionary, found %s",
92 kwdict
->ob_type
->tp_name
);
95 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
101 PyDoc_STRVAR(apply_doc
,
102 "apply(object[, args[, kwargs]]) -> value\n\
104 Call a callable object with positional arguments taken from the tuple args,\n\
105 and keyword arguments taken from the optional dictionary kwargs.\n\
106 Note that classes are callable, as are instances with a __call__() method.");
110 builtin_callable(PyObject
*self
, PyObject
*v
)
112 return PyBool_FromLong((long)PyCallable_Check(v
));
115 PyDoc_STRVAR(callable_doc
,
116 "callable(object) -> bool\n\
118 Return whether the object is callable (i.e., some kind of function).\n\
119 Note that classes are callable, as are instances with a __call__() method.");
123 builtin_filter(PyObject
*self
, PyObject
*args
)
125 PyObject
*func
, *seq
, *result
, *it
;
126 int len
; /* guess for result list size */
129 if (!PyArg_ParseTuple(args
, "OO:filter", &func
, &seq
))
132 /* Strings and tuples return a result of the same type. */
133 if (PyString_Check(seq
))
134 return filterstring(func
, seq
);
135 if (PyTuple_Check(seq
))
136 return filtertuple(func
, seq
);
139 it
= PyObject_GetIter(seq
);
143 /* Guess a result list size. */
144 len
= -1; /* unknown */
145 if (PySequence_Check(seq
) &&
146 seq
->ob_type
->tp_as_sequence
->sq_length
) {
147 len
= PySequence_Size(seq
);
152 len
= 8; /* arbitrary */
154 /* Get a result list. */
155 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
156 /* Eww - can modify the list in-place. */
161 result
= PyList_New(len
);
166 /* Build the result list. */
169 PyObject
*item
, *good
;
172 item
= PyIter_Next(it
);
174 if (PyErr_Occurred())
179 if (func
== Py_None
) {
184 PyObject
*arg
= Py_BuildValue("(O)", item
);
189 good
= PyEval_CallObject(func
, arg
);
196 ok
= PyObject_IsTrue(good
);
200 PyList_SET_ITEM(result
, j
, item
);
202 int status
= PyList_Append(result
, item
);
214 /* Cut back result list if len is too big. */
215 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
228 PyDoc_STRVAR(filter_doc
,
229 "filter(function or None, sequence) -> list, tuple, or string\n"
231 "Return those items of sequence for which function(item) is true. If\n"
232 "function is None, return the items that are true. If sequence is a tuple\n"
233 "or string, return the same type, else return a list.");
236 builtin_chr(PyObject
*self
, PyObject
*args
)
241 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
243 if (x
< 0 || x
>= 256) {
244 PyErr_SetString(PyExc_ValueError
,
245 "chr() arg not in range(256)");
249 return PyString_FromStringAndSize(s
, 1);
252 PyDoc_STRVAR(chr_doc
,
253 "chr(i) -> character\n\
255 Return a string of one character with ordinal i; 0 <= i < 256.");
258 #ifdef Py_USING_UNICODE
260 builtin_unichr(PyObject
*self
, PyObject
*args
)
265 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
268 #ifdef Py_UNICODE_WIDE
269 if (x
< 0 || x
> 0x10ffff) {
270 PyErr_SetString(PyExc_ValueError
,
271 "unichr() arg not in range(0x110000) "
272 "(wide Python build)");
276 if (x
< 0 || x
> 0xffff) {
277 PyErr_SetString(PyExc_ValueError
,
278 "unichr() arg not in range(0x10000) "
279 "(narrow Python build)");
285 /* UCS-2 character */
286 s
[0] = (Py_UNICODE
) x
;
287 return PyUnicode_FromUnicode(s
, 1);
290 #ifndef Py_UNICODE_WIDE
291 /* UCS-4 character. store as two surrogate characters */
293 s
[0] = 0xD800 + (Py_UNICODE
) (x
>> 10);
294 s
[1] = 0xDC00 + (Py_UNICODE
) (x
& 0x03FF);
295 return PyUnicode_FromUnicode(s
, 2);
297 s
[0] = (Py_UNICODE
)x
;
298 return PyUnicode_FromUnicode(s
, 1);
303 PyDoc_STRVAR(unichr_doc
,
304 "unichr(i) -> Unicode character\n\
306 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
311 builtin_cmp(PyObject
*self
, PyObject
*args
)
316 if (!PyArg_ParseTuple(args
, "OO:cmp", &a
, &b
))
318 if (PyObject_Cmp(a
, b
, &c
) < 0)
320 return PyInt_FromLong((long)c
);
323 PyDoc_STRVAR(cmp_doc
,
324 "cmp(x, y) -> integer\n\
326 Return negative if x<y, zero if x==y, positive if x>y.");
330 builtin_coerce(PyObject
*self
, PyObject
*args
)
335 if (!PyArg_ParseTuple(args
, "OO:coerce", &v
, &w
))
337 if (PyNumber_Coerce(&v
, &w
) < 0)
339 res
= Py_BuildValue("(OO)", v
, w
);
345 PyDoc_STRVAR(coerce_doc
,
346 "coerce(x, y) -> None or (x1, y1)\n\
348 When x and y can be coerced to values of the same type, return a tuple\n\
349 containing the coerced values. When they can't be coerced, return None.");
353 builtin_compile(PyObject
*self
, PyObject
*args
)
359 int dont_inherit
= 0;
360 int supplied_flags
= 0;
363 if (!PyArg_ParseTuple(args
, "sss|ii:compile", &str
, &filename
,
364 &startstr
, &supplied_flags
, &dont_inherit
))
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'");
379 if (supplied_flags
& ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
)) {
380 PyErr_SetString(PyExc_ValueError
,
381 "compile(): unrecognised flags");
384 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
386 cf
.cf_flags
= supplied_flags
;
388 PyEval_MergeCompilerFlags(&cf
);
390 return Py_CompileStringFlags(str
, filename
, start
, &cf
);
393 PyDoc_STRVAR(compile_doc
,
394 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
396 Compile the source string (a Python module, statement or expression)\n\
397 into a code object that can be executed by the exec statement or eval().\n\
398 The filename will be used for run-time error messages.\n\
399 The mode must be 'exec' to compile a module, 'single' to compile a\n\
400 single (interactive) statement, or 'eval' to compile an expression.\n\
401 The flags argument, if present, controls which future statements influence\n\
402 the compilation of the code.\n\
403 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
404 the effects of any future statements in effect in the code calling\n\
405 compile; if absent or zero these statements do influence the compilation,\n\
406 in addition to any features explicitly specified.");
409 builtin_dir(PyObject
*self
, PyObject
*args
)
411 PyObject
*arg
= NULL
;
413 if (!PyArg_ParseTuple(args
, "|O:dir", &arg
))
415 return PyObject_Dir(arg
);
418 PyDoc_STRVAR(dir_doc
,
419 "dir([object]) -> list of strings\n"
421 "Return an alphabetized list of names comprising (some of) the attributes\n"
422 "of the given object, and of attributes reachable from it:\n"
424 "No argument: the names in the current scope.\n"
425 "Module object: the module attributes.\n"
426 "Type or class object: its attributes, and recursively the attributes of\n"
428 "Otherwise: its attributes, its class's attributes, and recursively the\n"
429 " attributes of its class's base classes.");
432 builtin_divmod(PyObject
*self
, PyObject
*args
)
436 if (!PyArg_ParseTuple(args
, "OO:divmod", &v
, &w
))
438 return PyNumber_Divmod(v
, w
);
441 PyDoc_STRVAR(divmod_doc
,
442 "divmod(x, y) -> (div, mod)\n\
444 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
448 builtin_eval(PyObject
*self
, PyObject
*args
)
451 PyObject
*globals
= Py_None
, *locals
= Py_None
;
455 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
457 &PyDict_Type
, &globals
,
458 &PyDict_Type
, &locals
))
460 if (globals
== Py_None
) {
461 globals
= PyEval_GetGlobals();
462 if (locals
== Py_None
)
463 locals
= PyEval_GetLocals();
465 else if (locals
== Py_None
)
468 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
469 if (PyDict_SetItemString(globals
, "__builtins__",
470 PyEval_GetBuiltins()) != 0)
474 if (PyCode_Check(cmd
)) {
475 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
476 PyErr_SetString(PyExc_TypeError
,
477 "code object passed to eval() may not contain free variables");
480 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
483 if (!PyString_Check(cmd
) &&
484 !PyUnicode_Check(cmd
)) {
485 PyErr_SetString(PyExc_TypeError
,
486 "eval() arg 1 must be a string or code object");
489 if (PyString_AsStringAndSize(cmd
, &str
, NULL
))
491 while (*str
== ' ' || *str
== '\t')
495 (void)PyEval_MergeCompilerFlags(&cf
);
496 return PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
499 PyDoc_STRVAR(eval_doc
,
500 "eval(source[, globals[, locals]]) -> value\n\
502 Evaluate the source in the context of globals and locals.\n\
503 The source may be a string representing a Python expression\n\
504 or a code object as returned by compile().\n\
505 The globals and locals are dictionaries, defaulting to the current\n\
506 globals and locals. If only globals is given, locals defaults to it.");
510 builtin_execfile(PyObject
*self
, PyObject
*args
)
513 PyObject
*globals
= Py_None
, *locals
= Py_None
;
519 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
521 &PyDict_Type
, &globals
,
522 &PyDict_Type
, &locals
))
524 if (globals
== Py_None
) {
525 globals
= PyEval_GetGlobals();
526 if (locals
== Py_None
)
527 locals
= PyEval_GetLocals();
529 else if (locals
== Py_None
)
531 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
532 if (PyDict_SetItemString(globals
, "__builtins__",
533 PyEval_GetBuiltins()) != 0)
538 /* Test for existence or directory. */
543 if ((d
= dirstat(filename
))!=nil
) {
545 werrstr("is a directory");
551 #elif defined(RISCOS)
552 if (object_exists(filename
)) {
558 #else /* standard Posix */
561 if (stat(filename
, &s
) == 0) {
562 if (S_ISDIR(s
.st_mode
))
563 # if defined(PY_OS2) && defined(PYCC_VACPP)
575 Py_BEGIN_ALLOW_THREADS
576 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
585 PyErr_SetFromErrno(PyExc_IOError
);
589 if (PyEval_MergeCompilerFlags(&cf
))
590 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
593 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
598 PyDoc_STRVAR(execfile_doc
,
599 "execfile(filename[, globals[, locals]])\n\
601 Read and execute a Python script from a file.\n\
602 The globals and locals are dictionaries, defaulting to the current\n\
603 globals and locals. If only globals is given, locals defaults to it.");
607 builtin_getattr(PyObject
*self
, PyObject
*args
)
609 PyObject
*v
, *result
, *dflt
= NULL
;
612 if (!PyArg_ParseTuple(args
, "OO|O:getattr", &v
, &name
, &dflt
))
614 #ifdef Py_USING_UNICODE
615 if (PyUnicode_Check(name
)) {
616 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
622 if (!PyString_Check(name
)) {
623 PyErr_SetString(PyExc_TypeError
,
624 "attribute name must be string");
627 result
= PyObject_GetAttr(v
, name
);
628 if (result
== NULL
&& dflt
!= NULL
&&
629 PyErr_ExceptionMatches(PyExc_AttributeError
))
638 PyDoc_STRVAR(getattr_doc
,
639 "getattr(object, name[, default]) -> value\n\
641 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
642 When a default argument is given, it is returned when the attribute doesn't\n\
643 exist; without it, an exception is raised in that case.");
647 builtin_globals(PyObject
*self
)
651 d
= PyEval_GetGlobals();
656 PyDoc_STRVAR(globals_doc
,
657 "globals() -> dictionary\n\
659 Return the dictionary containing the current scope's global variables.");
663 builtin_hasattr(PyObject
*self
, PyObject
*args
)
668 if (!PyArg_ParseTuple(args
, "OO:hasattr", &v
, &name
))
670 #ifdef Py_USING_UNICODE
671 if (PyUnicode_Check(name
)) {
672 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
678 if (!PyString_Check(name
)) {
679 PyErr_SetString(PyExc_TypeError
,
680 "attribute name must be string");
683 v
= PyObject_GetAttr(v
, name
);
694 PyDoc_STRVAR(hasattr_doc
,
695 "hasattr(object, name) -> bool\n\
697 Return whether the object has an attribute with the given name.\n\
698 (This is done by calling getattr(object, name) and catching exceptions.)");
702 builtin_id(PyObject
*self
, PyObject
*v
)
704 return PyLong_FromVoidPtr(v
);
708 "id(object) -> integer\n\
710 Return the identity of an object. This is guaranteed to be unique among\n\
711 simultaneously existing objects. (Hint: it's the object's memory address.)");
715 builtin_map(PyObject
*self
, PyObject
*args
)
718 PyObject
*it
; /* the iterator object */
719 int saw_StopIteration
; /* bool: did the iterator end? */
722 PyObject
*func
, *result
;
723 sequence
*seqs
= NULL
, *sqp
;
727 n
= PyTuple_Size(args
);
729 PyErr_SetString(PyExc_TypeError
,
730 "map() requires at least two args");
734 func
= PyTuple_GetItem(args
, 0);
737 if (func
== Py_None
&& n
== 1) {
738 /* map(None, S) is the same as list(S). */
739 return PySequence_List(PyTuple_GetItem(args
, 1));
742 /* Get space for sequence descriptors. Must NULL out the iterator
743 * pointers so that jumping to Fail_2 later doesn't see trash.
745 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
749 for (i
= 0; i
< n
; ++i
) {
750 seqs
[i
].it
= (PyObject
*)NULL
;
751 seqs
[i
].saw_StopIteration
= 0;
754 /* Do a first pass to obtain iterators for the arguments, and set len
755 * to the largest of their lengths.
758 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
763 curseq
= PyTuple_GetItem(args
, i
+1);
764 sqp
->it
= PyObject_GetIter(curseq
);
765 if (sqp
->it
== NULL
) {
766 static char errmsg
[] =
767 "argument %d to map() must support iteration";
768 char errbuf
[sizeof(errmsg
) + 25];
769 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
770 PyErr_SetString(PyExc_TypeError
, errbuf
);
775 curlen
= -1; /* unknown */
776 if (PySequence_Check(curseq
) &&
777 curseq
->ob_type
->tp_as_sequence
->sq_length
) {
778 curlen
= PySequence_Size(curseq
);
783 curlen
= 8; /* arbitrary */
788 /* Get space for the result list. */
789 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
792 /* Iterate over the sequences until all have stopped. */
794 PyObject
*alist
, *item
=NULL
, *value
;
797 if (func
== Py_None
&& n
== 1)
799 else if ((alist
= PyTuple_New(n
)) == NULL
)
802 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
803 if (sqp
->saw_StopIteration
) {
808 item
= PyIter_Next(sqp
->it
);
812 if (PyErr_Occurred()) {
818 sqp
->saw_StopIteration
= 1;
822 PyTuple_SET_ITEM(alist
, j
, item
);
830 if (numactive
== 0) {
838 value
= PyEval_CallObject(func
, alist
);
844 int status
= PyList_Append(result
, value
);
849 else if (PyList_SetItem(result
, i
, value
) < 0)
853 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
864 for (i
= 0; i
< n
; ++i
)
865 Py_XDECREF(seqs
[i
].it
);
870 PyDoc_STRVAR(map_doc
,
871 "map(function, sequence[, sequence, ...]) -> list\n\
873 Return a list of the results of applying the function to the items of\n\
874 the argument sequence(s). If more than one sequence is given, the\n\
875 function is called with an argument list consisting of the corresponding\n\
876 item of each sequence, substituting None for missing values when not all\n\
877 sequences have the same length. If the function is None, return a list of\n\
878 the items of the sequence (or a list of tuples if more than one sequence).");
882 builtin_setattr(PyObject
*self
, PyObject
*args
)
888 if (!PyArg_ParseTuple(args
, "OOO:setattr", &v
, &name
, &value
))
890 if (PyObject_SetAttr(v
, name
, value
) != 0)
896 PyDoc_STRVAR(setattr_doc
,
897 "setattr(object, name, value)\n\
899 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
904 builtin_delattr(PyObject
*self
, PyObject
*args
)
909 if (!PyArg_ParseTuple(args
, "OO:delattr", &v
, &name
))
911 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
917 PyDoc_STRVAR(delattr_doc
,
918 "delattr(object, name)\n\
920 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
925 builtin_hash(PyObject
*self
, PyObject
*v
)
929 x
= PyObject_Hash(v
);
932 return PyInt_FromLong(x
);
935 PyDoc_STRVAR(hash_doc
,
936 "hash(object) -> integer\n\
938 Return a hash value for the object. Two objects with the same value have\n\
939 the same hash value. The reverse is not necessarily true, but likely.");
943 builtin_hex(PyObject
*self
, PyObject
*v
)
947 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
948 nb
->nb_hex
== NULL
) {
949 PyErr_SetString(PyExc_TypeError
,
950 "hex() argument can't be converted to hex");
953 return (*nb
->nb_hex
)(v
);
956 PyDoc_STRVAR(hex_doc
,
957 "hex(number) -> string\n\
959 Return the hexadecimal representation of an integer or long integer.");
962 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
965 builtin_input(PyObject
*self
, PyObject
*args
)
970 PyObject
*globals
, *locals
;
972 line
= builtin_raw_input(self
, args
);
975 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
977 while (*str
== ' ' || *str
== '\t')
979 globals
= PyEval_GetGlobals();
980 locals
= PyEval_GetLocals();
981 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
982 if (PyDict_SetItemString(globals
, "__builtins__",
983 PyEval_GetBuiltins()) != 0)
986 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
991 PyDoc_STRVAR(input_doc
,
992 "input([prompt]) -> value\n\
994 Equivalent to eval(raw_input(prompt)).");
998 builtin_intern(PyObject
*self
, PyObject
*args
)
1001 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1004 PyString_InternInPlace(&s
);
1008 PyDoc_STRVAR(intern_doc
,
1009 "intern(string) -> string\n\
1011 ``Intern'' the given string. This enters the string in the (global)\n\
1012 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1013 Return the string itself or the previously interned string object with the\n\
1018 builtin_iter(PyObject
*self
, PyObject
*args
)
1020 PyObject
*v
, *w
= NULL
;
1022 if (!PyArg_ParseTuple(args
, "O|O:iter", &v
, &w
))
1025 return PyObject_GetIter(v
);
1026 if (!PyCallable_Check(v
)) {
1027 PyErr_SetString(PyExc_TypeError
,
1028 "iter(v, w): v must be callable");
1031 return PyCallIter_New(v
, w
);
1034 PyDoc_STRVAR(iter_doc
,
1035 "iter(collection) -> iterator\n\
1036 iter(callable, sentinel) -> iterator\n\
1038 Get an iterator from an object. In the first form, the argument must\n\
1039 supply its own iterator, or be a sequence.\n\
1040 In the second form, the callable is called until it returns the sentinel.");
1044 builtin_len(PyObject
*self
, PyObject
*v
)
1048 res
= PyObject_Size(v
);
1049 if (res
< 0 && PyErr_Occurred())
1051 return PyInt_FromLong(res
);
1054 PyDoc_STRVAR(len_doc
,
1055 "len(object) -> integer\n\
1057 Return the number of items of a sequence or mapping.");
1061 builtin_locals(PyObject
*self
)
1065 d
= PyEval_GetLocals();
1070 PyDoc_STRVAR(locals_doc
,
1071 "locals() -> dictionary\n\
1073 Return the dictionary containing the current scope's local variables.");
1077 min_max(PyObject
*args
, int op
)
1079 PyObject
*v
, *w
, *x
, *it
;
1081 if (PyTuple_Size(args
) > 1)
1083 else if (!PyArg_ParseTuple(args
, "O:min/max", &v
))
1086 it
= PyObject_GetIter(v
);
1090 w
= NULL
; /* the result */
1092 x
= PyIter_Next(it
);
1094 if (PyErr_Occurred()) {
1105 int cmp
= PyObject_RichCompareBool(x
, w
, op
);
1121 PyErr_SetString(PyExc_ValueError
,
1122 "min() or max() arg is an empty sequence");
1128 builtin_min(PyObject
*self
, PyObject
*v
)
1130 return min_max(v
, Py_LT
);
1133 PyDoc_STRVAR(min_doc
,
1134 "min(sequence) -> value\n\
1135 min(a, b, c, ...) -> value\n\
1137 With a single sequence argument, return its smallest item.\n\
1138 With two or more arguments, return the smallest argument.");
1142 builtin_max(PyObject
*self
, PyObject
*v
)
1144 return min_max(v
, Py_GT
);
1147 PyDoc_STRVAR(max_doc
,
1148 "max(sequence) -> value\n\
1149 max(a, b, c, ...) -> value\n\
1151 With a single sequence argument, return its largest item.\n\
1152 With two or more arguments, return the largest argument.");
1156 builtin_oct(PyObject
*self
, PyObject
*v
)
1158 PyNumberMethods
*nb
;
1160 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1161 nb
->nb_oct
== NULL
) {
1162 PyErr_SetString(PyExc_TypeError
,
1163 "oct() argument can't be converted to oct");
1166 return (*nb
->nb_oct
)(v
);
1169 PyDoc_STRVAR(oct_doc
,
1170 "oct(number) -> string\n\
1172 Return the octal representation of an integer or long integer.");
1176 builtin_ord(PyObject
*self
, PyObject
* obj
)
1181 if (PyString_Check(obj
)) {
1182 size
= PyString_GET_SIZE(obj
);
1184 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1185 return PyInt_FromLong(ord
);
1187 #ifdef Py_USING_UNICODE
1188 } else if (PyUnicode_Check(obj
)) {
1189 size
= PyUnicode_GET_SIZE(obj
);
1191 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1192 return PyInt_FromLong(ord
);
1196 PyErr_Format(PyExc_TypeError
,
1197 "ord() expected string of length 1, but " \
1198 "%.200s found", obj
->ob_type
->tp_name
);
1202 PyErr_Format(PyExc_TypeError
,
1203 "ord() expected a character, "
1204 "but string of length %d found",
1209 PyDoc_STRVAR(ord_doc
,
1210 "ord(c) -> integer\n\
1212 Return the integer ordinal of a one-character string.");
1216 builtin_pow(PyObject
*self
, PyObject
*args
)
1218 PyObject
*v
, *w
, *z
= Py_None
;
1220 if (!PyArg_ParseTuple(args
, "OO|O:pow", &v
, &w
, &z
))
1222 return PyNumber_Power(v
, w
, z
);
1225 PyDoc_STRVAR(pow_doc
,
1226 "pow(x, y[, z]) -> number\n\
1228 With two arguments, equivalent to x**y. With three arguments,\n\
1229 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1232 /* Return number of items in range/xrange (lo, hi, step). step > 0
1233 * required. Return a value < 0 if & only if the true value is too
1234 * large to fit in a signed long.
1237 get_len_of_range(long lo
, long hi
, long step
)
1239 /* -------------------------------------------------------------
1240 If lo >= hi, the range is empty.
1241 Else if n values are in the range, the last one is
1242 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1243 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1244 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1245 the RHS is non-negative and so truncation is the same as the
1246 floor. Letting M be the largest positive long, the worst case
1247 for the RHS numerator is hi=M, lo=-M-1, and then
1248 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1249 precision to compute the RHS exactly.
1250 ---------------------------------------------------------------*/
1253 unsigned long uhi
= (unsigned long)hi
;
1254 unsigned long ulo
= (unsigned long)lo
;
1255 unsigned long diff
= uhi
- ulo
- 1;
1256 n
= (long)(diff
/ (unsigned long)step
+ 1);
1262 builtin_range(PyObject
*self
, PyObject
*args
)
1264 long ilow
= 0, ihigh
= 0, istep
= 1;
1270 if (PyTuple_Size(args
) <= 1) {
1271 if (!PyArg_ParseTuple(args
,
1272 "l;range() requires 1-3 int arguments",
1277 if (!PyArg_ParseTuple(args
,
1278 "ll|l;range() requires 1-3 int arguments",
1279 &ilow
, &ihigh
, &istep
))
1283 PyErr_SetString(PyExc_ValueError
, "range() arg 3 must not be zero");
1287 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1289 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1291 if (bign
< 0 || (long)n
!= bign
) {
1292 PyErr_SetString(PyExc_OverflowError
,
1293 "range() result has too many items");
1299 for (i
= 0; i
< n
; i
++) {
1300 PyObject
*w
= PyInt_FromLong(ilow
);
1305 PyList_SET_ITEM(v
, i
, w
);
1311 PyDoc_STRVAR(range_doc
,
1312 "range([start,] stop[, step]) -> list of integers\n\
1314 Return a list containing an arithmetic progression of integers.\n\
1315 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1316 When step is given, it specifies the increment (or decrement).\n\
1317 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1318 These are exactly the valid indices for a list of 4 elements.");
1322 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1327 if (!PyArg_ParseTuple(args
, "|O:[raw_]input", &v
))
1329 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin
&&
1330 PyFile_AsFile(PySys_GetObject("stdout")) == stdout
&&
1331 isatty(fileno(stdin
)) && isatty(fileno(stdout
))) {
1337 po
= PyObject_Str(v
);
1340 prompt
= PyString_AsString(po
);
1348 s
= PyOS_Readline(prompt
);
1351 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1355 PyErr_SetNone(PyExc_EOFError
);
1358 else { /* strip trailing '\n' */
1359 size_t len
= strlen(s
);
1360 if (len
> INT_MAX
) {
1361 PyErr_SetString(PyExc_OverflowError
, "input too long");
1365 result
= PyString_FromStringAndSize(s
, (int)(len
-1));
1372 f
= PySys_GetObject("stdout");
1374 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
1377 if (Py_FlushLine() != 0 ||
1378 PyFile_WriteObject(v
, f
, Py_PRINT_RAW
) != 0)
1381 f
= PySys_GetObject("stdin");
1383 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdin");
1386 return PyFile_GetLine(f
, -1);
1389 PyDoc_STRVAR(raw_input_doc
,
1390 "raw_input([prompt]) -> string\n\
1392 Read a string from standard input. The trailing newline is stripped.\n\
1393 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1394 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1395 is printed without a trailing newline before reading.");
1399 builtin_reduce(PyObject
*self
, PyObject
*args
)
1401 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1403 if (!PyArg_ParseTuple(args
, "OO|O:reduce", &func
, &seq
, &result
))
1408 it
= PyObject_GetIter(seq
);
1410 PyErr_SetString(PyExc_TypeError
,
1411 "reduce() arg 2 must support iteration");
1416 if ((args
= PyTuple_New(2)) == NULL
)
1422 if (args
->ob_refcnt
> 1) {
1424 if ((args
= PyTuple_New(2)) == NULL
)
1428 op2
= PyIter_Next(it
);
1430 if (PyErr_Occurred())
1438 PyTuple_SetItem(args
, 0, result
);
1439 PyTuple_SetItem(args
, 1, op2
);
1440 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1448 PyErr_SetString(PyExc_TypeError
,
1449 "reduce() of empty sequence with no initial value");
1461 PyDoc_STRVAR(reduce_doc
,
1462 "reduce(function, sequence[, initial]) -> value\n\
1464 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1465 from left to right, so as to reduce the sequence to a single value.\n\
1466 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1467 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1468 of the sequence in the calculation, and serves as a default when the\n\
1469 sequence is empty.");
1473 builtin_reload(PyObject
*self
, PyObject
*v
)
1475 return PyImport_ReloadModule(v
);
1478 PyDoc_STRVAR(reload_doc
,
1479 "reload(module) -> module\n\
1481 Reload the module. The module must have been successfully imported before.");
1485 builtin_repr(PyObject
*self
, PyObject
*v
)
1487 return PyObject_Repr(v
);
1490 PyDoc_STRVAR(repr_doc
,
1491 "repr(object) -> string\n\
1493 Return the canonical string representation of the object.\n\
1494 For most object types, eval(repr(object)) == object.");
1498 builtin_round(PyObject
*self
, PyObject
*args
)
1505 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1523 return PyFloat_FromDouble(x
);
1526 PyDoc_STRVAR(round_doc
,
1527 "round(number[, ndigits]) -> floating point number\n\
1529 Round a number to a given precision in decimal digits (default 0 digits).\n\
1530 This always returns a floating point number. Precision may be negative.");
1534 builtin_vars(PyObject
*self
, PyObject
*args
)
1539 if (!PyArg_ParseTuple(args
, "|O:vars", &v
))
1542 d
= PyEval_GetLocals();
1544 if (!PyErr_Occurred())
1545 PyErr_SetString(PyExc_SystemError
,
1552 d
= PyObject_GetAttrString(v
, "__dict__");
1554 PyErr_SetString(PyExc_TypeError
,
1555 "vars() argument must have __dict__ attribute");
1562 PyDoc_STRVAR(vars_doc
,
1563 "vars([object]) -> dictionary\n\
1565 Without arguments, equivalent to locals().\n\
1566 With an argument, equivalent to object.__dict__.");
1569 builtin_isinstance(PyObject
*self
, PyObject
*args
)
1575 if (!PyArg_ParseTuple(args
, "OO:isinstance", &inst
, &cls
))
1578 retval
= PyObject_IsInstance(inst
, cls
);
1581 return PyBool_FromLong(retval
);
1584 PyDoc_STRVAR(isinstance_doc
,
1585 "isinstance(object, class-or-type-or-tuple) -> bool\n\
1587 Return whether an object is an instance of a class or of a subclass thereof.\n\
1588 With a type as second argument, return whether that is the object's type.\n\
1589 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1590 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
1594 builtin_issubclass(PyObject
*self
, PyObject
*args
)
1600 if (!PyArg_ParseTuple(args
, "OO:issubclass", &derived
, &cls
))
1603 retval
= PyObject_IsSubclass(derived
, cls
);
1606 return PyBool_FromLong(retval
);
1609 PyDoc_STRVAR(issubclass_doc
,
1610 "issubclass(C, B) -> bool\n\
1612 Return whether class C is a subclass (i.e., a derived class) of class B.");
1616 builtin_zip(PyObject
*self
, PyObject
*args
)
1619 const int itemsize
= PySequence_Length(args
);
1621 PyObject
*itlist
; /* tuple of iterators */
1622 int len
; /* guess at result length */
1625 PyErr_SetString(PyExc_TypeError
,
1626 "zip() requires at least one sequence");
1629 /* args must be a tuple */
1630 assert(PyTuple_Check(args
));
1632 /* Guess at result length: the shortest of the input lengths.
1633 If some argument refuses to say, we refuse to guess too, lest
1634 an argument like xrange(sys.maxint) lead us astray.*/
1635 len
= -1; /* unknown */
1636 for (i
= 0; i
< itemsize
; ++i
) {
1637 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
1638 int thislen
= PySequence_Length(item
);
1644 else if (len
< 0 || thislen
< len
)
1648 /* allocate result list */
1650 len
= 10; /* arbitrary */
1651 if ((ret
= PyList_New(len
)) == NULL
)
1654 /* obtain iterators */
1655 itlist
= PyTuple_New(itemsize
);
1658 for (i
= 0; i
< itemsize
; ++i
) {
1659 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
1660 PyObject
*it
= PyObject_GetIter(item
);
1662 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1663 PyErr_Format(PyExc_TypeError
,
1664 "zip argument #%d must support iteration",
1666 goto Fail_ret_itlist
;
1668 PyTuple_SET_ITEM(itlist
, i
, it
);
1671 /* build result into ret list */
1672 for (i
= 0; ; ++i
) {
1674 PyObject
*next
= PyTuple_New(itemsize
);
1676 goto Fail_ret_itlist
;
1678 for (j
= 0; j
< itemsize
; j
++) {
1679 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
1680 PyObject
*item
= PyIter_Next(it
);
1682 if (PyErr_Occurred()) {
1690 PyTuple_SET_ITEM(next
, j
, item
);
1694 PyList_SET_ITEM(ret
, i
, next
);
1696 int status
= PyList_Append(ret
, next
);
1700 goto Fail_ret_itlist
;
1705 if (ret
!= NULL
&& i
< len
) {
1706 /* The list is too big. */
1707 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
1720 PyDoc_STRVAR(zip_doc
,
1721 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
1723 Return a list of tuples, where each tuple contains the i-th element\n\
1724 from each of the argument sequences. The returned list is truncated\n\
1725 in length to the length of the shortest argument sequence.");
1728 static PyMethodDef builtin_methods
[] = {
1729 {"__import__", builtin___import__
, METH_VARARGS
, import_doc
},
1730 {"abs", builtin_abs
, METH_O
, abs_doc
},
1731 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
1732 {"callable", builtin_callable
, METH_O
, callable_doc
},
1733 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
1734 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
1735 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
1736 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
1737 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
1738 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
1739 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
1740 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
1741 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
1742 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
1743 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
1744 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
1745 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
1746 {"hash", builtin_hash
, METH_O
, hash_doc
},
1747 {"hex", builtin_hex
, METH_O
, hex_doc
},
1748 {"id", builtin_id
, METH_O
, id_doc
},
1749 {"input", builtin_input
, METH_VARARGS
, input_doc
},
1750 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
1751 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
1752 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
1753 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
1754 {"len", builtin_len
, METH_O
, len_doc
},
1755 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
1756 {"map", builtin_map
, METH_VARARGS
, map_doc
},
1757 {"max", builtin_max
, METH_VARARGS
, max_doc
},
1758 {"min", builtin_min
, METH_VARARGS
, min_doc
},
1759 {"oct", builtin_oct
, METH_O
, oct_doc
},
1760 {"ord", builtin_ord
, METH_O
, ord_doc
},
1761 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
1762 {"range", builtin_range
, METH_VARARGS
, range_doc
},
1763 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
1764 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
1765 {"reload", builtin_reload
, METH_O
, reload_doc
},
1766 {"repr", builtin_repr
, METH_O
, repr_doc
},
1767 {"round", builtin_round
, METH_VARARGS
, round_doc
},
1768 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
1769 #ifdef Py_USING_UNICODE
1770 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
1772 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
1773 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
1777 PyDoc_STRVAR(builtin_doc
,
1778 "Built-in functions, exceptions, and other objects.\n\
1780 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
1783 _PyBuiltin_Init(void)
1785 PyObject
*mod
, *dict
, *debug
;
1786 mod
= Py_InitModule4("__builtin__", builtin_methods
,
1787 builtin_doc
, (PyObject
*)NULL
,
1788 PYTHON_API_VERSION
);
1791 dict
= PyModule_GetDict(mod
);
1793 #define SETBUILTIN(NAME, OBJECT) \
1794 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
1797 SETBUILTIN("None", Py_None
);
1798 SETBUILTIN("Ellipsis", Py_Ellipsis
);
1799 SETBUILTIN("NotImplemented", Py_NotImplemented
);
1800 SETBUILTIN("False", Py_False
);
1801 SETBUILTIN("True", Py_True
);
1802 SETBUILTIN("basestring", &PyBaseString_Type
);
1803 SETBUILTIN("bool", &PyBool_Type
);
1804 SETBUILTIN("buffer", &PyBuffer_Type
);
1805 SETBUILTIN("classmethod", &PyClassMethod_Type
);
1806 #ifndef WITHOUT_COMPLEX
1807 SETBUILTIN("complex", &PyComplex_Type
);
1809 SETBUILTIN("dict", &PyDict_Type
);
1810 SETBUILTIN("enumerate", &PyEnum_Type
);
1811 SETBUILTIN("float", &PyFloat_Type
);
1812 SETBUILTIN("property", &PyProperty_Type
);
1813 SETBUILTIN("int", &PyInt_Type
);
1814 SETBUILTIN("list", &PyList_Type
);
1815 SETBUILTIN("long", &PyLong_Type
);
1816 SETBUILTIN("object", &PyBaseObject_Type
);
1817 SETBUILTIN("slice", &PySlice_Type
);
1818 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
1819 SETBUILTIN("str", &PyString_Type
);
1820 SETBUILTIN("super", &PySuper_Type
);
1821 SETBUILTIN("tuple", &PyTuple_Type
);
1822 SETBUILTIN("type", &PyType_Type
);
1823 SETBUILTIN("xrange", &PyRange_Type
);
1825 /* Note that open() is just an alias of file(). */
1826 SETBUILTIN("open", &PyFile_Type
);
1827 SETBUILTIN("file", &PyFile_Type
);
1828 #ifdef Py_USING_UNICODE
1829 SETBUILTIN("unicode", &PyUnicode_Type
);
1831 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
1832 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
1842 /* Helper for filter(): filter a tuple through a function */
1845 filtertuple(PyObject
*func
, PyObject
*tuple
)
1849 int len
= PyTuple_Size(tuple
);
1856 if ((result
= PyTuple_New(len
)) == NULL
)
1859 for (i
= j
= 0; i
< len
; ++i
) {
1860 PyObject
*item
, *good
;
1863 if ((item
= PyTuple_GetItem(tuple
, i
)) == NULL
)
1865 if (func
== Py_None
) {
1870 PyObject
*arg
= Py_BuildValue("(O)", item
);
1873 good
= PyEval_CallObject(func
, arg
);
1878 ok
= PyObject_IsTrue(good
);
1882 if (PyTuple_SetItem(result
, j
++, item
) < 0)
1887 if (_PyTuple_Resize(&result
, j
) < 0)
1898 /* Helper for filter(): filter a string through a function */
1901 filterstring(PyObject
*func
, PyObject
*strobj
)
1905 int len
= PyString_Size(strobj
);
1907 if (func
== Py_None
) {
1908 /* No character is ever false -- share input string */
1912 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
1915 for (i
= j
= 0; i
< len
; ++i
) {
1916 PyObject
*item
, *arg
, *good
;
1919 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
1922 arg
= Py_BuildValue("(O)", item
);
1927 good
= PyEval_CallObject(func
, arg
);
1933 ok
= PyObject_IsTrue(good
);
1936 PyString_AS_STRING((PyStringObject
*)result
)[j
++] =
1937 PyString_AS_STRING((PyStringObject
*)item
)[0];
1942 _PyString_Resize(&result
, j
);