2 /* Built-in functions */
17 static PyObject
*filterstring(PyObject
*, PyObject
*);
18 static PyObject
*filtertuple (PyObject
*, PyObject
*);
21 builtin___import__(PyObject
*self
, PyObject
*args
)
24 PyObject
*globals
= NULL
;
25 PyObject
*locals
= NULL
;
26 PyObject
*fromlist
= NULL
;
28 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
29 &name
, &globals
, &locals
, &fromlist
))
31 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
34 static char import_doc
[] =
35 "__import__(name, globals, locals, fromlist) -> module\n\
37 Import a module. The globals are only used to determine the context;\n\
38 they are not modified. The locals are currently unused. The fromlist\n\
39 should be a list of names to emulate ``from name import ...'', or an\n\
40 empty list to emulate ``import name''.\n\
41 When importing a module from a package, note that __import__('A.B', ...)\n\
42 returns package A when fromlist is empty, but its submodule B when\n\
43 fromlist is not empty.";
47 builtin_abs(PyObject
*self
, PyObject
*args
)
51 if (!PyArg_ParseTuple(args
, "O:abs", &v
))
53 return PyNumber_Absolute(v
);
56 static char abs_doc
[] =
57 "abs(number) -> number\n\
59 Return the absolute value of the argument.";
63 builtin_apply(PyObject
*self
, PyObject
*args
)
65 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
66 PyObject
*t
= NULL
, *retval
= NULL
;
68 if (!PyArg_ParseTuple(args
, "O|OO:apply", &func
, &alist
, &kwdict
))
71 if (!PyTuple_Check(alist
)) {
72 if (!PySequence_Check(alist
)) {
73 PyErr_Format(PyExc_TypeError
,
74 "apply() arg 2 expect sequence, found %s",
75 alist
->ob_type
->tp_name
);
78 t
= PySequence_Tuple(alist
);
84 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
85 PyErr_Format(PyExc_TypeError
,
86 "apply() arg 3 expected dictionary, found %s",
87 kwdict
->ob_type
->tp_name
);
90 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
96 static char apply_doc
[] =
97 "apply(object[, args[, kwargs]]) -> value\n\
99 Call a callable object with positional arguments taken from the tuple args,\n\
100 and keyword arguments taken from the optional dictionary kwargs.\n\
101 Note that classes are callable, as are instances with a __call__() method.";
105 builtin_buffer(PyObject
*self
, PyObject
*args
)
109 int size
= Py_END_OF_BUFFER
;
111 if ( !PyArg_ParseTuple(args
, "O|ii:buffer", &ob
, &offset
, &size
) )
113 return PyBuffer_FromObject(ob
, offset
, size
);
116 static char buffer_doc
[] =
117 "buffer(object [, offset[, size]]) -> object\n\
119 Create a new buffer object which references the given object.\n\
120 The buffer will reference a slice of the target object from the\n\
121 start of the object (or at the specified offset). The slice will\n\
122 extend to the end of the target object (or with the specified size).";
126 builtin_unicode(PyObject
*self
, PyObject
*args
)
129 char *encoding
= NULL
;
132 if ( !PyArg_ParseTuple(args
, "O|ss:unicode", &v
, &encoding
, &errors
) )
134 return PyUnicode_FromEncodedObject(v
, encoding
, errors
);
137 static char unicode_doc
[] =
138 "unicode(string [, encoding[, errors]]) -> object\n\
140 Create a new Unicode object from the given encoded string.\n\
141 encoding defaults to the current default string encoding and \n\
142 errors, defining the error handling, to 'strict'.";
146 builtin_callable(PyObject
*self
, PyObject
*args
)
150 if (!PyArg_ParseTuple(args
, "O:callable", &v
))
152 return PyInt_FromLong((long)PyCallable_Check(v
));
155 static char callable_doc
[] =
156 "callable(object) -> Boolean\n\
158 Return whether the object is callable (i.e., some kind of function).\n\
159 Note that classes are callable, as are instances with a __call__() method.";
163 builtin_filter(PyObject
*self
, PyObject
*args
)
165 PyObject
*func
, *seq
, *result
;
166 PySequenceMethods
*sqf
;
170 if (!PyArg_ParseTuple(args
, "OO:filter", &func
, &seq
))
173 if (PyString_Check(seq
)) {
174 PyObject
*r
= filterstring(func
, seq
);
178 if (PyTuple_Check(seq
)) {
179 PyObject
*r
= filtertuple(func
, seq
);
183 sqf
= seq
->ob_type
->tp_as_sequence
;
184 if (sqf
== NULL
|| sqf
->sq_length
== NULL
|| sqf
->sq_item
== NULL
) {
185 PyErr_SetString(PyExc_TypeError
,
186 "filter() arg 2 must be a sequence");
190 if ((len
= (*sqf
->sq_length
)(seq
)) < 0)
193 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
198 if ((result
= PyList_New(len
)) == NULL
)
202 for (i
= j
= 0; ; ++i
) {
203 PyObject
*item
, *good
;
206 if ((item
= (*sqf
->sq_item
)(seq
, i
)) == NULL
) {
207 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
214 if (func
== Py_None
) {
219 PyObject
*arg
= Py_BuildValue("(O)", item
);
222 good
= PyEval_CallObject(func
, arg
);
229 ok
= PyObject_IsTrue(good
);
233 if (PyList_SetItem(result
, j
++, item
) < 0)
237 int status
= PyList_Append(result
, item
);
249 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
260 static char filter_doc
[] =
261 "filter(function, sequence) -> list\n\
263 Return a list containing those items of sequence for which function(item)\n\
264 is true. If function is None, return a list of items that are true.";
268 builtin_chr(PyObject
*self
, PyObject
*args
)
273 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
275 if (x
< 0 || x
>= 256) {
276 PyErr_SetString(PyExc_ValueError
,
277 "chr() arg not in range(256)");
281 return PyString_FromStringAndSize(s
, 1);
284 static char chr_doc
[] =
285 "chr(i) -> character\n\
287 Return a string of one character with ordinal i; 0 <= i < 256.";
291 builtin_unichr(PyObject
*self
, PyObject
*args
)
296 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
298 if (x
< 0 || x
>= 65536) {
299 PyErr_SetString(PyExc_ValueError
,
300 "unichr() arg not in range(65536)");
303 s
[0] = (Py_UNICODE
)x
;
304 return PyUnicode_FromUnicode(s
, 1);
307 static char unichr_doc
[] =
308 "unichr(i) -> Unicode character\n\
310 Return a Unicode string of one character with ordinal i; 0 <= i < 65536.";
314 builtin_cmp(PyObject
*self
, PyObject
*args
)
319 if (!PyArg_ParseTuple(args
, "OO:cmp", &a
, &b
))
321 if (PyObject_Cmp(a
, b
, &c
) < 0)
323 return PyInt_FromLong((long)c
);
326 static char cmp_doc
[] =
327 "cmp(x, y) -> integer\n\
329 Return negative if x<y, zero if x==y, positive if x>y.";
333 builtin_coerce(PyObject
*self
, PyObject
*args
)
338 if (!PyArg_ParseTuple(args
, "OO:coerce", &v
, &w
))
340 if (PyNumber_Coerce(&v
, &w
) < 0)
342 res
= Py_BuildValue("(OO)", v
, w
);
348 static char coerce_doc
[] =
349 "coerce(x, y) -> None or (x1, y1)\n\
351 When x and y can be coerced to values of the same type, return a tuple\n\
352 containing the coerced values. When they can't be coerced, return None.";
356 builtin_compile(PyObject
*self
, PyObject
*args
)
363 if (!PyArg_ParseTuple(args
, "sss:compile", &str
, &filename
, &startstr
))
365 if (strcmp(startstr
, "exec") == 0)
366 start
= Py_file_input
;
367 else if (strcmp(startstr
, "eval") == 0)
368 start
= Py_eval_input
;
369 else if (strcmp(startstr
, "single") == 0)
370 start
= Py_single_input
;
372 PyErr_SetString(PyExc_ValueError
,
373 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
376 return Py_CompileString(str
, filename
, start
);
379 static char compile_doc
[] =
380 "compile(source, filename, mode) -> code object\n\
382 Compile the source string (a Python module, statement or expression)\n\
383 into a code object that can be executed by the exec statement or eval().\n\
384 The filename will be used for run-time error messages.\n\
385 The mode must be 'exec' to compile a module, 'single' to compile a\n\
386 single (interactive) statement, or 'eval' to compile an expression.";
389 #ifndef WITHOUT_COMPLEX
392 complex_from_string(PyObject
*v
)
394 extern double strtod(const char *, char **);
395 const char *s
, *start
;
397 double x
=0.0, y
=0.0, z
;
398 int got_re
=0, got_im
=0, done
=0;
402 char buffer
[256]; /* For errors */
406 if (PyString_Check(v
)) {
407 s
= PyString_AS_STRING(v
);
408 len
= PyString_GET_SIZE(v
);
410 else if (PyUnicode_Check(v
)) {
411 if (PyUnicode_GET_SIZE(v
) >= sizeof(s_buffer
)) {
412 PyErr_SetString(PyExc_ValueError
,
413 "complex() literal too large to convert");
416 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
417 PyUnicode_GET_SIZE(v
),
422 len
= (int)strlen(s
);
424 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
425 PyErr_SetString(PyExc_TypeError
,
426 "complex() arg is not a string");
430 /* position on first nonblank */
432 while (*s
&& isspace(Py_CHARMASK(*s
)))
435 PyErr_SetString(PyExc_ValueError
,
436 "complex() arg is an empty string");
447 if (s
-start
!= len
) {
450 "complex() arg contains a null byte");
453 if(!done
) sw_error
=1;
460 if (done
) sw_error
=1;
462 if ( *s
=='\0'||*s
=='+'||*s
=='-' ||
463 isspace(Py_CHARMASK(*s
)) ) sw_error
=1;
468 if (got_im
|| done
) {
480 if (*s
!='+' && *s
!='-' )
485 if (isspace(Py_CHARMASK(*s
))) {
486 while (*s
&& isspace(Py_CHARMASK(*s
)))
495 (*s
=='.' || isdigit(Py_CHARMASK(*s
)));
496 if (done
||!digit_or_dot
) {
501 PyFPE_START_PROTECT("strtod", return 0)
502 z
= strtod(s
, &end
) ;
506 "float() out of range: %.150s", s
);
513 if (*s
=='J' || *s
=='j') {
522 /* accept a real part */
530 } /* end of switch */
532 } while (*s
!='\0' && !sw_error
);
535 PyErr_SetString(PyExc_ValueError
,
536 "complex() arg is a malformed string");
540 return PyComplex_FromDoubles(x
,y
);
544 builtin_complex(PyObject
*self
, PyObject
*args
)
546 PyObject
*r
, *i
, *tmp
;
547 PyNumberMethods
*nbr
, *nbi
= NULL
;
552 if (!PyArg_ParseTuple(args
, "O|O:complex", &r
, &i
))
554 if (PyString_Check(r
) || PyUnicode_Check(r
))
555 return complex_from_string(r
);
556 if ((nbr
= r
->ob_type
->tp_as_number
) == NULL
||
557 nbr
->nb_float
== NULL
||
559 ((nbi
= i
->ob_type
->tp_as_number
) == NULL
||
560 nbi
->nb_float
== NULL
))) {
561 PyErr_SetString(PyExc_TypeError
,
562 "complex() arg can't be converted to complex");
565 /* XXX Hack to support classes with __complex__ method */
566 if (PyInstance_Check(r
)) {
567 static PyObject
*complexstr
;
569 if (complexstr
== NULL
) {
570 complexstr
= PyString_InternFromString("__complex__");
571 if (complexstr
== NULL
)
574 f
= PyObject_GetAttr(r
, complexstr
);
578 PyObject
*args
= Py_BuildValue("()");
581 r
= PyEval_CallObject(f
, args
);
589 if (PyComplex_Check(r
)) {
590 cr
= ((PyComplexObject
*)r
)->cval
;
596 tmp
= PyNumber_Float(r
);
602 if (!PyFloat_Check(tmp
)) {
603 PyErr_SetString(PyExc_TypeError
,
604 "float(r) didn't return a float");
608 cr
.real
= PyFloat_AsDouble(tmp
);
616 else if (PyComplex_Check(i
))
617 ci
= ((PyComplexObject
*)i
)->cval
;
619 tmp
= (*nbi
->nb_float
)(i
);
622 ci
.real
= PyFloat_AsDouble(tmp
);
628 return PyComplex_FromCComplex(cr
);
631 static char complex_doc
[] =
632 "complex(real[, imag]) -> complex number\n\
634 Create a complex number from a real part and an optional imaginary part.\n\
635 This is equivalent to (real + imag*1j) where imag defaults to 0.";
641 builtin_dir(PyObject
*self
, PyObject
*args
)
643 static char *attrlist
[] = {"__members__", "__methods__", NULL
};
644 PyObject
*v
= NULL
, *l
= NULL
, *m
= NULL
;
649 if (!PyArg_ParseTuple(args
, "|O:dir", &v
))
652 x
= PyEval_GetLocals();
655 l
= PyMapping_Keys(x
);
660 d
= PyObject_GetAttrString(v
, "__dict__");
664 l
= PyMapping_Keys(d
);
674 for (s
= attrlist
; *s
!= NULL
; s
++) {
675 m
= PyObject_GetAttrString(v
, *s
);
681 x
= PySequence_GetItem(m
, i
);
686 if (PyList_Append(l
, x
) != 0) {
696 if (PyList_Sort(l
) != 0)
704 static char dir_doc
[] =
705 "dir([object]) -> list of strings\n\
707 Return an alphabetized list of names comprising (some of) the attributes\n\
708 of the given object. Without an argument, the names in the current scope\n\
709 are listed. With an instance argument, only the instance attributes are\n\
710 returned. With a class argument, attributes of the base class are not\n\
711 returned. For other types or arguments, this may list members or methods.";
715 builtin_divmod(PyObject
*self
, PyObject
*args
)
719 if (!PyArg_ParseTuple(args
, "OO:divmod", &v
, &w
))
721 return PyNumber_Divmod(v
, w
);
724 static char divmod_doc
[] =
725 "divmod(x, y) -> (div, mod)\n\
727 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
731 builtin_eval(PyObject
*self
, PyObject
*args
)
734 PyObject
*globals
= Py_None
, *locals
= Py_None
;
737 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
739 &PyDict_Type
, &globals
,
740 &PyDict_Type
, &locals
))
742 if (globals
== Py_None
) {
743 globals
= PyEval_GetGlobals();
744 if (locals
== Py_None
)
745 locals
= PyEval_GetLocals();
747 else if (locals
== Py_None
)
749 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
750 if (PyDict_SetItemString(globals
, "__builtins__",
751 PyEval_GetBuiltins()) != 0)
754 if (PyCode_Check(cmd
))
755 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
756 if (!PyString_Check(cmd
) &&
757 !PyUnicode_Check(cmd
)) {
758 PyErr_SetString(PyExc_TypeError
,
759 "eval() arg 1 must be a string or code object");
762 if (PyString_AsStringAndSize(cmd
, &str
, NULL
))
764 while (*str
== ' ' || *str
== '\t')
766 return PyRun_String(str
, Py_eval_input
, globals
, locals
);
769 static char eval_doc
[] =
770 "eval(source[, globals[, locals]]) -> value\n\
772 Evaluate the source in the context of globals and locals.\n\
773 The source may be a string representing a Python expression\n\
774 or a code object as returned by compile().\n\
775 The globals and locals are dictionaries, defaulting to the current\n\
776 globals and locals. If only globals is given, locals defaults to it.";
780 builtin_execfile(PyObject
*self
, PyObject
*args
)
783 PyObject
*globals
= Py_None
, *locals
= Py_None
;
787 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
789 &PyDict_Type
, &globals
,
790 &PyDict_Type
, &locals
))
792 if (globals
== Py_None
) {
793 globals
= PyEval_GetGlobals();
794 if (locals
== Py_None
)
795 locals
= PyEval_GetLocals();
797 else if (locals
== Py_None
)
799 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
800 if (PyDict_SetItemString(globals
, "__builtins__",
801 PyEval_GetBuiltins()) != 0)
804 Py_BEGIN_ALLOW_THREADS
805 fp
= fopen(filename
, "r");
808 PyErr_SetFromErrno(PyExc_IOError
);
811 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
, locals
, 1);
815 static char execfile_doc
[] =
816 "execfile(filename[, globals[, locals]])\n\
818 Read and execute a Python script from a file.\n\
819 The globals and locals are dictionaries, defaulting to the current\n\
820 globals and locals. If only globals is given, locals defaults to it.";
824 builtin_getattr(PyObject
*self
, PyObject
*args
)
826 PyObject
*v
, *result
, *dflt
= NULL
;
829 if (!PyArg_ParseTuple(args
, "OO|O:getattr", &v
, &name
, &dflt
))
831 result
= PyObject_GetAttr(v
, name
);
832 if (result
== NULL
&& dflt
!= NULL
) {
840 static char getattr_doc
[] =
841 "getattr(object, name[, default]) -> value\n\
843 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
844 When a default argument is given, it is returned when the attribute doesn't\n\
845 exist; without it, an exception is raised in that case.";
849 builtin_globals(PyObject
*self
, PyObject
*args
)
853 if (!PyArg_ParseTuple(args
, ":globals"))
855 d
= PyEval_GetGlobals();
860 static char globals_doc
[] =
861 "globals() -> dictionary\n\
863 Return the dictionary containing the current scope's global variables.";
867 builtin_hasattr(PyObject
*self
, PyObject
*args
)
872 if (!PyArg_ParseTuple(args
, "OO:hasattr", &v
, &name
))
874 v
= PyObject_GetAttr(v
, name
);
885 static char hasattr_doc
[] =
886 "hasattr(object, name) -> Boolean\n\
888 Return whether the object has an attribute with the given name.\n\
889 (This is done by calling getattr(object, name) and catching exceptions.)";
893 builtin_id(PyObject
*self
, PyObject
*args
)
897 if (!PyArg_ParseTuple(args
, "O:id", &v
))
899 return PyLong_FromVoidPtr(v
);
902 static char id_doc
[] =
903 "id(object) -> integer\n\
905 Return the identity of an object. This is guaranteed to be unique among\n\
906 simultaneously existing objects. (Hint: it's the object's memory address.)";
910 builtin_map(PyObject
*self
, PyObject
*args
)
914 PySequenceMethods
*sqf
;
918 PyObject
*func
, *result
;
919 sequence
*seqs
= NULL
, *sqp
;
923 n
= PyTuple_Size(args
);
925 PyErr_SetString(PyExc_TypeError
,
926 "map() requires at least two args");
930 func
= PyTuple_GetItem(args
, 0);
933 if (func
== Py_None
&& n
== 1) {
934 /* map(None, S) is the same as list(S). */
935 return PySequence_List(PyTuple_GetItem(args
, 1));
938 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
943 for (len
= 0, i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
945 PySequenceMethods
*sqf
;
947 if ((sqp
->seq
= PyTuple_GetItem(args
, i
+ 1)) == NULL
)
950 sqp
->sqf
= sqf
= sqp
->seq
->ob_type
->tp_as_sequence
;
952 sqf
->sq_length
== NULL
||
953 sqf
->sq_item
== NULL
)
955 static char errmsg
[] =
956 "argument %d to map() must be a sequence object";
957 char errbuf
[sizeof(errmsg
) + 25];
959 sprintf(errbuf
, errmsg
, i
+2);
960 PyErr_SetString(PyExc_TypeError
, errbuf
);
964 if ((curlen
= sqp
->len
= (*sqp
->sqf
->sq_length
)(sqp
->seq
)) < 0)
971 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
975 PyObject
*alist
, *item
=NULL
, *value
;
978 if (func
== Py_None
&& n
== 1)
981 if ((alist
= PyTuple_New(n
)) == NULL
)
985 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
991 item
= (*sqp
->sqf
->sq_item
)(sqp
->seq
, i
);
993 if (PyErr_ExceptionMatches(
1011 if (PyTuple_SetItem(alist
, j
, item
) < 0) {
1030 if (func
== Py_None
)
1033 value
= PyEval_CallObject(func
, alist
);
1039 int status
= PyList_Append(result
, value
);
1045 if (PyList_SetItem(result
, i
, value
) < 0)
1050 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1059 if (seqs
) PyMem_DEL(seqs
);
1063 static char map_doc
[] =
1064 "map(function, sequence[, sequence, ...]) -> list\n\
1066 Return a list of the results of applying the function to the items of\n\
1067 the argument sequence(s). If more than one sequence is given, the\n\
1068 function is called with an argument list consisting of the corresponding\n\
1069 item of each sequence, substituting None for missing values when not all\n\
1070 sequences have the same length. If the function is None, return a list of\n\
1071 the items of the sequence (or a list of tuples if more than one sequence).";
1075 builtin_setattr(PyObject
*self
, PyObject
*args
)
1081 if (!PyArg_ParseTuple(args
, "OOO:setattr", &v
, &name
, &value
))
1083 if (PyObject_SetAttr(v
, name
, value
) != 0)
1089 static char setattr_doc
[] =
1090 "setattr(object, name, value)\n\
1092 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1097 builtin_delattr(PyObject
*self
, PyObject
*args
)
1102 if (!PyArg_ParseTuple(args
, "OO:delattr", &v
, &name
))
1104 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1110 static char delattr_doc
[] =
1111 "delattr(object, name)\n\
1113 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1118 builtin_hash(PyObject
*self
, PyObject
*args
)
1123 if (!PyArg_ParseTuple(args
, "O:hash", &v
))
1125 x
= PyObject_Hash(v
);
1128 return PyInt_FromLong(x
);
1131 static char hash_doc
[] =
1132 "hash(object) -> integer\n\
1134 Return a hash value for the object. Two objects with the same value have\n\
1135 the same hash value. The reverse is not necessarily true, but likely.";
1139 builtin_hex(PyObject
*self
, PyObject
*args
)
1142 PyNumberMethods
*nb
;
1144 if (!PyArg_ParseTuple(args
, "O:hex", &v
))
1147 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1148 nb
->nb_hex
== NULL
) {
1149 PyErr_SetString(PyExc_TypeError
,
1150 "hex() argument can't be converted to hex");
1153 return (*nb
->nb_hex
)(v
);
1156 static char hex_doc
[] =
1157 "hex(number) -> string\n\
1159 Return the hexadecimal representation of an integer or long integer.";
1162 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1165 builtin_input(PyObject
*self
, PyObject
*args
)
1170 PyObject
*globals
, *locals
;
1172 line
= builtin_raw_input(self
, args
);
1175 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1177 while (*str
== ' ' || *str
== '\t')
1179 globals
= PyEval_GetGlobals();
1180 locals
= PyEval_GetLocals();
1181 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1182 if (PyDict_SetItemString(globals
, "__builtins__",
1183 PyEval_GetBuiltins()) != 0)
1186 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
1191 static char input_doc
[] =
1192 "input([prompt]) -> value\n\
1194 Equivalent to eval(raw_input(prompt)).";
1198 builtin_intern(PyObject
*self
, PyObject
*args
)
1201 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1204 PyString_InternInPlace(&s
);
1208 static char intern_doc
[] =
1209 "intern(string) -> string\n\
1211 ``Intern'' the given string. This enters the string in the (global)\n\
1212 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1213 Return the string itself or the previously interned string object with the\n\
1218 builtin_int(PyObject
*self
, PyObject
*args
)
1221 int base
= -909; /* unlikely! */
1223 if (!PyArg_ParseTuple(args
, "O|i:int", &v
, &base
))
1226 return PyNumber_Int(v
);
1227 else if (PyString_Check(v
))
1228 return PyInt_FromString(PyString_AS_STRING(v
), NULL
, base
);
1229 else if (PyUnicode_Check(v
))
1230 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(v
),
1231 PyUnicode_GET_SIZE(v
),
1234 PyErr_SetString(PyExc_TypeError
,
1235 "int() can't convert non-string with explicit base");
1240 static char int_doc
[] =
1241 "int(x[, base]) -> integer\n\
1243 Convert a string or number to an integer, if possible. A floating point\n\
1244 argument will be truncated towards zero (this does not include a string\n\
1245 representation of a floating point number!) When converting a string, use\n\
1246 the optional base. It is an error to supply a base when converting a\n\
1251 builtin_long(PyObject
*self
, PyObject
*args
)
1254 int base
= -909; /* unlikely! */
1256 if (!PyArg_ParseTuple(args
, "O|i:long", &v
, &base
))
1259 return PyNumber_Long(v
);
1260 else if (PyString_Check(v
))
1261 return PyLong_FromString(PyString_AS_STRING(v
), NULL
, base
);
1262 else if (PyUnicode_Check(v
))
1263 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(v
),
1264 PyUnicode_GET_SIZE(v
),
1267 PyErr_SetString(PyExc_TypeError
,
1268 "long() can't convert non-string with explicit base");
1273 static char long_doc
[] =
1274 "long(x) -> long integer\n\
1275 long(x, base) -> long integer\n\
1277 Convert a string or number to a long integer, if possible. A floating\n\
1278 point argument will be truncated towards zero (this does not include a\n\
1279 string representation of a floating point number!) When converting a\n\
1280 string, use the given base. It is an error to supply a base when\n\
1281 converting a non-string.";
1285 builtin_float(PyObject
*self
, PyObject
*args
)
1289 if (!PyArg_ParseTuple(args
, "O:float", &v
))
1291 if (PyString_Check(v
))
1292 return PyFloat_FromString(v
, NULL
);
1293 return PyNumber_Float(v
);
1296 static char float_doc
[] =
1297 "float(x) -> floating point number\n\
1299 Convert a string or number to a floating point number, if possible.";
1303 builtin_len(PyObject
*self
, PyObject
*args
)
1308 if (!PyArg_ParseTuple(args
, "O:len", &v
))
1310 res
= PyObject_Size(v
);
1311 if (res
< 0 && PyErr_Occurred())
1313 return PyInt_FromLong(res
);
1316 static char len_doc
[] =
1317 "len(object) -> integer\n\
1319 Return the number of items of a sequence or mapping.";
1323 builtin_list(PyObject
*self
, PyObject
*args
)
1327 if (!PyArg_ParseTuple(args
, "O:list", &v
))
1329 return PySequence_List(v
);
1332 static char list_doc
[] =
1333 "list(sequence) -> list\n\
1335 Return a new list whose items are the same as those of the argument sequence.";
1339 builtin_slice(PyObject
*self
, PyObject
*args
)
1341 PyObject
*start
, *stop
, *step
;
1343 start
= stop
= step
= NULL
;
1345 if (!PyArg_ParseTuple(args
, "O|OO:slice", &start
, &stop
, &step
))
1348 /* This swapping of stop and start is to maintain similarity with
1354 return PySlice_New(start
, stop
, step
);
1357 static char slice_doc
[] =
1358 "slice([start,] stop[, step]) -> slice object\n\
1360 Create a slice object. This is used for slicing by the Numeric extensions.";
1364 builtin_locals(PyObject
*self
, PyObject
*args
)
1368 if (!PyArg_ParseTuple(args
, ":locals"))
1370 d
= PyEval_GetLocals();
1375 static char locals_doc
[] =
1376 "locals() -> dictionary\n\
1378 Return the dictionary containing the current scope's local variables.";
1382 min_max(PyObject
*args
, int op
)
1385 PyObject
*v
, *w
, *x
;
1386 PySequenceMethods
*sq
;
1388 if (PyTuple_Size(args
) > 1)
1390 else if (!PyArg_ParseTuple(args
, "O:min/max", &v
))
1392 sq
= v
->ob_type
->tp_as_sequence
;
1393 if (sq
== NULL
|| sq
->sq_item
== NULL
) {
1394 PyErr_SetString(PyExc_TypeError
,
1395 "min() or max() arg must be a sequence");
1399 for (i
= 0; ; i
++) {
1400 x
= (*sq
->sq_item
)(v
, i
); /* Implies INCREF */
1402 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1412 int cmp
= PyObject_RichCompareBool(x
, w
, op
);
1427 PyErr_SetString(PyExc_ValueError
,
1428 "min() or max() arg is an empty sequence");
1433 builtin_min(PyObject
*self
, PyObject
*v
)
1435 return min_max(v
, Py_LT
);
1438 static char min_doc
[] =
1439 "min(sequence) -> value\n\
1440 min(a, b, c, ...) -> value\n\
1442 With a single sequence argument, return its smallest item.\n\
1443 With two or more arguments, return the smallest argument.";
1447 builtin_max(PyObject
*self
, PyObject
*v
)
1449 return min_max(v
, Py_GT
);
1452 static char max_doc
[] =
1453 "max(sequence) -> value\n\
1454 max(a, b, c, ...) -> value\n\
1456 With a single sequence argument, return its largest item.\n\
1457 With two or more arguments, return the largest argument.";
1461 builtin_oct(PyObject
*self
, PyObject
*args
)
1464 PyNumberMethods
*nb
;
1466 if (!PyArg_ParseTuple(args
, "O:oct", &v
))
1468 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1469 nb
->nb_oct
== NULL
) {
1470 PyErr_SetString(PyExc_TypeError
,
1471 "oct() argument can't be converted to oct");
1474 return (*nb
->nb_oct
)(v
);
1477 static char oct_doc
[] =
1478 "oct(number) -> string\n\
1480 Return the octal representation of an integer or long integer.";
1484 builtin_open(PyObject
*self
, PyObject
*args
)
1491 if (!PyArg_ParseTuple(args
, "s|si:open", &name
, &mode
, &bufsize
))
1493 f
= PyFile_FromString(name
, mode
);
1495 PyFile_SetBufSize(f
, bufsize
);
1499 static char open_doc
[] =
1500 "open(filename[, mode[, buffering]]) -> file object\n\
1502 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1503 writing or appending. The file will be created if it doesn't exist\n\
1504 when opened for writing or appending; it will be truncated when\n\
1505 opened for writing. Add a 'b' to the mode for binary files.\n\
1506 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1507 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1508 buffered, and larger numbers specify the buffer size.";
1512 builtin_ord(PyObject
*self
, PyObject
*args
)
1518 if (!PyArg_ParseTuple(args
, "O:ord", &obj
))
1521 if (PyString_Check(obj
)) {
1522 size
= PyString_GET_SIZE(obj
);
1524 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1525 return PyInt_FromLong(ord
);
1527 } else if (PyUnicode_Check(obj
)) {
1528 size
= PyUnicode_GET_SIZE(obj
);
1530 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1531 return PyInt_FromLong(ord
);
1534 PyErr_Format(PyExc_TypeError
,
1535 "ord() expected string of length 1, but " \
1536 "%.200s found", obj
->ob_type
->tp_name
);
1540 PyErr_Format(PyExc_TypeError
,
1541 "ord() expected a character, "
1542 "but string of length %d found",
1547 static char ord_doc
[] =
1548 "ord(c) -> integer\n\
1550 Return the integer ordinal of a one-character string.";
1554 builtin_pow(PyObject
*self
, PyObject
*args
)
1556 PyObject
*v
, *w
, *z
= Py_None
;
1558 if (!PyArg_ParseTuple(args
, "OO|O:pow", &v
, &w
, &z
))
1560 return PyNumber_Power(v
, w
, z
);
1563 static char pow_doc
[] =
1564 "pow(x, y[, z]) -> number\n\
1566 With two arguments, equivalent to x**y. With three arguments,\n\
1567 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1570 /* Return number of items in range/xrange (lo, hi, step). step > 0
1571 * required. Return a value < 0 if & only if the true value is too
1572 * large to fit in a signed long.
1575 get_len_of_range(long lo
, long hi
, long step
)
1577 /* -------------------------------------------------------------
1578 If lo >= hi, the range is empty.
1579 Else if n values are in the range, the last one is
1580 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1581 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1582 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1583 the RHS is non-negative and so truncation is the same as the
1584 floor. Letting M be the largest positive long, the worst case
1585 for the RHS numerator is hi=M, lo=-M-1, and then
1586 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1587 precision to compute the RHS exactly.
1588 ---------------------------------------------------------------*/
1591 unsigned long uhi
= (unsigned long)hi
;
1592 unsigned long ulo
= (unsigned long)lo
;
1593 unsigned long diff
= uhi
- ulo
- 1;
1594 n
= (long)(diff
/ (unsigned long)step
+ 1);
1600 builtin_range(PyObject
*self
, PyObject
*args
)
1602 long ilow
= 0, ihigh
= 0, istep
= 1;
1608 if (PyTuple_Size(args
) <= 1) {
1609 if (!PyArg_ParseTuple(args
,
1610 "l;range() requires 1-3 int arguments",
1615 if (!PyArg_ParseTuple(args
,
1616 "ll|l;range() requires 1-3 int arguments",
1617 &ilow
, &ihigh
, &istep
))
1621 PyErr_SetString(PyExc_ValueError
, "range() arg 3 must not be zero");
1625 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1627 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1629 if (bign
< 0 || (long)n
!= bign
) {
1630 PyErr_SetString(PyExc_OverflowError
,
1631 "range() result has too many items");
1637 for (i
= 0; i
< n
; i
++) {
1638 PyObject
*w
= PyInt_FromLong(ilow
);
1643 PyList_SET_ITEM(v
, i
, w
);
1649 static char range_doc
[] =
1650 "range([start,] stop[, step]) -> list of integers\n\
1652 Return a list containing an arithmetic progression of integers.\n\
1653 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1654 When step is given, it specifies the increment (or decrement).\n\
1655 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1656 These are exactly the valid indices for a list of 4 elements.";
1660 builtin_xrange(PyObject
*self
, PyObject
*args
)
1662 long ilow
= 0, ihigh
= 0, istep
= 1;
1665 if (PyTuple_Size(args
) <= 1) {
1666 if (!PyArg_ParseTuple(args
,
1667 "l;xrange() requires 1-3 int arguments",
1672 if (!PyArg_ParseTuple(args
,
1673 "ll|l;xrange() requires 1-3 int arguments",
1674 &ilow
, &ihigh
, &istep
))
1678 PyErr_SetString(PyExc_ValueError
, "xrange() arg 3 must not be zero");
1682 n
= get_len_of_range(ilow
, ihigh
, istep
);
1684 n
= get_len_of_range(ihigh
, ilow
, -istep
);
1686 PyErr_SetString(PyExc_OverflowError
,
1687 "xrange() result has too many items");
1690 return PyRange_New(ilow
, n
, istep
, 1);
1693 static char xrange_doc
[] =
1694 "xrange([start,] stop[, step]) -> xrange object\n\
1696 Like range(), but instead of returning a list, returns an object that\n\
1697 generates the numbers in the range on demand. This is slightly slower\n\
1698 than range() but more memory efficient.";
1702 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1707 if (!PyArg_ParseTuple(args
, "|O:[raw_]input", &v
))
1709 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin
&&
1710 PyFile_AsFile(PySys_GetObject("stdout")) == stdout
&&
1711 isatty(fileno(stdin
)) && isatty(fileno(stdout
))) {
1717 po
= PyObject_Str(v
);
1720 prompt
= PyString_AsString(po
);
1728 s
= PyOS_Readline(prompt
);
1731 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1735 PyErr_SetNone(PyExc_EOFError
);
1738 else { /* strip trailing '\n' */
1739 size_t len
= strlen(s
);
1740 if (len
> INT_MAX
) {
1741 PyErr_SetString(PyExc_OverflowError
, "input too long");
1745 result
= PyString_FromStringAndSize(s
, (int)(len
-1));
1752 f
= PySys_GetObject("stdout");
1754 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
1757 if (Py_FlushLine() != 0 ||
1758 PyFile_WriteObject(v
, f
, Py_PRINT_RAW
) != 0)
1761 f
= PySys_GetObject("stdin");
1763 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdin");
1766 return PyFile_GetLine(f
, -1);
1769 static char raw_input_doc
[] =
1770 "raw_input([prompt]) -> string\n\
1772 Read a string from standard input. The trailing newline is stripped.\n\
1773 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1774 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1775 is printed without a trailing newline before reading.";
1779 builtin_reduce(PyObject
*self
, PyObject
*args
)
1781 PyObject
*seq
, *func
, *result
= NULL
;
1782 PySequenceMethods
*sqf
;
1785 if (!PyArg_ParseTuple(args
, "OO|O:reduce", &func
, &seq
, &result
))
1790 sqf
= seq
->ob_type
->tp_as_sequence
;
1791 if (sqf
== NULL
|| sqf
->sq_item
== NULL
) {
1792 PyErr_SetString(PyExc_TypeError
,
1793 "reduce() arg 2 must be a sequence");
1797 if ((args
= PyTuple_New(2)) == NULL
)
1800 for (i
= 0; ; ++i
) {
1803 if (args
->ob_refcnt
> 1) {
1805 if ((args
= PyTuple_New(2)) == NULL
)
1809 if ((op2
= (*sqf
->sq_item
)(seq
, i
)) == NULL
) {
1810 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1820 PyTuple_SetItem(args
, 0, result
);
1821 PyTuple_SetItem(args
, 1, op2
);
1822 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1830 PyErr_SetString(PyExc_TypeError
,
1831 "reduce() of empty sequence with no initial value");
1841 static char reduce_doc
[] =
1842 "reduce(function, sequence[, initial]) -> value\n\
1844 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1845 from left to right, so as to reduce the sequence to a single value.\n\
1846 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1847 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1848 of the sequence in the calculation, and serves as a default when the\n\
1849 sequence is empty.";
1853 builtin_reload(PyObject
*self
, PyObject
*args
)
1857 if (!PyArg_ParseTuple(args
, "O:reload", &v
))
1859 return PyImport_ReloadModule(v
);
1862 static char reload_doc
[] =
1863 "reload(module) -> module\n\
1865 Reload the module. The module must have been successfully imported before.";
1869 builtin_repr(PyObject
*self
, PyObject
*args
)
1873 if (!PyArg_ParseTuple(args
, "O:repr", &v
))
1875 return PyObject_Repr(v
);
1878 static char repr_doc
[] =
1879 "repr(object) -> string\n\
1881 Return the canonical string representation of the object.\n\
1882 For most object types, eval(repr(object)) == object.";
1886 builtin_round(PyObject
*self
, PyObject
*args
)
1893 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1911 return PyFloat_FromDouble(x
);
1914 static char round_doc
[] =
1915 "round(number[, ndigits]) -> floating point number\n\
1917 Round a number to a given precision in decimal digits (default 0 digits).\n\
1918 This always returns a floating point number. Precision may be negative.";
1922 builtin_str(PyObject
*self
, PyObject
*args
)
1926 if (!PyArg_ParseTuple(args
, "O:str", &v
))
1928 return PyObject_Str(v
);
1931 static char str_doc
[] =
1932 "str(object) -> string\n\
1934 Return a nice string representation of the object.\n\
1935 If the argument is a string, the return value is the same object.";
1939 builtin_tuple(PyObject
*self
, PyObject
*args
)
1943 if (!PyArg_ParseTuple(args
, "O:tuple", &v
))
1945 return PySequence_Tuple(v
);
1948 static char tuple_doc
[] =
1949 "tuple(sequence) -> list\n\
1951 Return a tuple whose items are the same as those of the argument sequence.\n\
1952 If the argument is a tuple, the return value is the same object.";
1956 builtin_type(PyObject
*self
, PyObject
*args
)
1960 if (!PyArg_ParseTuple(args
, "O:type", &v
))
1962 v
= (PyObject
*)v
->ob_type
;
1967 static char type_doc
[] =
1968 "type(object) -> type object\n\
1970 Return the type of the object.";
1974 builtin_vars(PyObject
*self
, PyObject
*args
)
1979 if (!PyArg_ParseTuple(args
, "|O:vars", &v
))
1982 d
= PyEval_GetLocals();
1984 if (!PyErr_Occurred())
1985 PyErr_SetString(PyExc_SystemError
,
1992 d
= PyObject_GetAttrString(v
, "__dict__");
1994 PyErr_SetString(PyExc_TypeError
,
1995 "vars() argument must have __dict__ attribute");
2002 static char vars_doc
[] =
2003 "vars([object]) -> dictionary\n\
2005 Without arguments, equivalent to locals().\n\
2006 With an argument, equivalent to object.__dict__.";
2009 abstract_issubclass(PyObject
*derived
, PyObject
*cls
, int first
)
2011 static PyObject
*__bases__
= NULL
;
2016 if (__bases__
== NULL
) {
2017 __bases__
= PyString_FromString("__bases__");
2018 if (__bases__
== NULL
)
2023 bases
= PyObject_GetAttr(cls
, __bases__
);
2024 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
2026 PyErr_SetString(PyExc_TypeError
,
2027 "issubclass() arg 2 must be a class");
2036 bases
= PyObject_GetAttr(derived
, __bases__
);
2037 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
2039 PyErr_SetString(PyExc_TypeError
,
2040 "issubclass() arg 1 must be a class");
2044 n
= PyTuple_GET_SIZE(bases
);
2045 for (i
= 0; i
< n
; i
++) {
2046 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
), cls
, 0);
2057 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2062 static PyObject
*__class__
= NULL
;
2065 if (!PyArg_ParseTuple(args
, "OO:isinstance", &inst
, &cls
))
2068 if (PyClass_Check(cls
)) {
2069 if (PyInstance_Check(inst
)) {
2071 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2072 retval
= PyClass_IsSubclass(inclass
, cls
);
2075 else if (PyType_Check(cls
)) {
2076 retval
= ((PyObject
*)(inst
->ob_type
) == cls
);
2078 else if (!PyInstance_Check(inst
)) {
2079 if (__class__
== NULL
) {
2080 __class__
= PyString_FromString("__class__");
2081 if (__class__
== NULL
)
2084 icls
= PyObject_GetAttr(inst
, __class__
);
2086 retval
= abstract_issubclass(icls
, cls
, 1);
2089 !PyErr_ExceptionMatches(PyExc_TypeError
))
2099 PyErr_SetString(PyExc_TypeError
,
2100 "isinstance() arg 2 must be a class or type");
2103 return PyInt_FromLong(retval
);
2106 static char isinstance_doc
[] =
2107 "isinstance(object, class-or-type) -> Boolean\n\
2109 Return whether an object is an instance of a class or of a subclass thereof.\n\
2110 With a type as second argument, return whether that is the object's type.";
2114 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2120 if (!PyArg_ParseTuple(args
, "OO:issubclass", &derived
, &cls
))
2123 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2124 retval
= abstract_issubclass(derived
, cls
, 1);
2130 if (!(retval
= (derived
== cls
)))
2131 retval
= PyClass_IsSubclass(derived
, cls
);
2134 return PyInt_FromLong(retval
);
2137 static char issubclass_doc
[] =
2138 "issubclass(C, B) -> Boolean\n\
2140 Return whether class C is a subclass (i.e., a derived class) of class B.";
2144 builtin_zip(PyObject
*self
, PyObject
*args
)
2147 int itemsize
= PySequence_Length(args
);
2151 PyErr_SetString(PyExc_TypeError
,
2152 "zip() requires at least one sequence");
2155 /* args must be a tuple */
2156 assert(PyTuple_Check(args
));
2158 if ((ret
= PyList_New(0)) == NULL
)
2162 PyObject
*next
= PyTuple_New(itemsize
);
2167 for (j
= 0; j
< itemsize
; j
++) {
2168 PyObject
*seq
= PyTuple_GET_ITEM(args
, j
);
2169 PyObject
*item
= PySequence_GetItem(seq
, i
);
2172 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2181 PyTuple_SET_ITEM(next
, j
, item
);
2183 PyList_Append(ret
, next
);
2190 static char zip_doc
[] =
2191 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2193 Return a list of tuples, where each tuple contains the i-th element\n\
2194 from each of the argument sequences. The returned list is truncated\n\
2195 in length to the length of the shortest argument sequence.";
2198 static PyMethodDef builtin_methods
[] = {
2199 {"__import__", builtin___import__
, 1, import_doc
},
2200 {"abs", builtin_abs
, 1, abs_doc
},
2201 {"apply", builtin_apply
, 1, apply_doc
},
2202 {"buffer", builtin_buffer
, 1, buffer_doc
},
2203 {"callable", builtin_callable
, 1, callable_doc
},
2204 {"chr", builtin_chr
, 1, chr_doc
},
2205 {"cmp", builtin_cmp
, 1, cmp_doc
},
2206 {"coerce", builtin_coerce
, 1, coerce_doc
},
2207 {"compile", builtin_compile
, 1, compile_doc
},
2208 #ifndef WITHOUT_COMPLEX
2209 {"complex", builtin_complex
, 1, complex_doc
},
2211 {"delattr", builtin_delattr
, 1, delattr_doc
},
2212 {"dir", builtin_dir
, 1, dir_doc
},
2213 {"divmod", builtin_divmod
, 1, divmod_doc
},
2214 {"eval", builtin_eval
, 1, eval_doc
},
2215 {"execfile", builtin_execfile
, 1, execfile_doc
},
2216 {"filter", builtin_filter
, 1, filter_doc
},
2217 {"float", builtin_float
, 1, float_doc
},
2218 {"getattr", builtin_getattr
, 1, getattr_doc
},
2219 {"globals", builtin_globals
, 1, globals_doc
},
2220 {"hasattr", builtin_hasattr
, 1, hasattr_doc
},
2221 {"hash", builtin_hash
, 1, hash_doc
},
2222 {"hex", builtin_hex
, 1, hex_doc
},
2223 {"id", builtin_id
, 1, id_doc
},
2224 {"input", builtin_input
, 1, input_doc
},
2225 {"intern", builtin_intern
, 1, intern_doc
},
2226 {"int", builtin_int
, 1, int_doc
},
2227 {"isinstance", builtin_isinstance
, 1, isinstance_doc
},
2228 {"issubclass", builtin_issubclass
, 1, issubclass_doc
},
2229 {"len", builtin_len
, 1, len_doc
},
2230 {"list", builtin_list
, 1, list_doc
},
2231 {"locals", builtin_locals
, 1, locals_doc
},
2232 {"long", builtin_long
, 1, long_doc
},
2233 {"map", builtin_map
, 1, map_doc
},
2234 {"max", builtin_max
, 1, max_doc
},
2235 {"min", builtin_min
, 1, min_doc
},
2236 {"oct", builtin_oct
, 1, oct_doc
},
2237 {"open", builtin_open
, 1, open_doc
},
2238 {"ord", builtin_ord
, 1, ord_doc
},
2239 {"pow", builtin_pow
, 1, pow_doc
},
2240 {"range", builtin_range
, 1, range_doc
},
2241 {"raw_input", builtin_raw_input
, 1, raw_input_doc
},
2242 {"reduce", builtin_reduce
, 1, reduce_doc
},
2243 {"reload", builtin_reload
, 1, reload_doc
},
2244 {"repr", builtin_repr
, 1, repr_doc
},
2245 {"round", builtin_round
, 1, round_doc
},
2246 {"setattr", builtin_setattr
, 1, setattr_doc
},
2247 {"slice", builtin_slice
, 1, slice_doc
},
2248 {"str", builtin_str
, 1, str_doc
},
2249 {"tuple", builtin_tuple
, 1, tuple_doc
},
2250 {"type", builtin_type
, 1, type_doc
},
2251 {"unicode", builtin_unicode
, 1, unicode_doc
},
2252 {"unichr", builtin_unichr
, 1, unichr_doc
},
2253 {"vars", builtin_vars
, 1, vars_doc
},
2254 {"xrange", builtin_xrange
, 1, xrange_doc
},
2255 {"zip", builtin_zip
, 1, zip_doc
},
2259 static char builtin_doc
[] =
2260 "Built-in functions, exceptions, and other objects.\n\
2262 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2265 _PyBuiltin_Init(void)
2267 PyObject
*mod
, *dict
, *debug
;
2268 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2269 builtin_doc
, (PyObject
*)NULL
,
2270 PYTHON_API_VERSION
);
2273 dict
= PyModule_GetDict(mod
);
2274 if (PyDict_SetItemString(dict
, "None", Py_None
) < 0)
2276 if (PyDict_SetItemString(dict
, "Ellipsis", Py_Ellipsis
) < 0)
2278 if (PyDict_SetItemString(dict
, "NotImplemented",
2279 Py_NotImplemented
) < 0)
2281 debug
= PyInt_FromLong(Py_OptimizeFlag
== 0);
2282 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2291 /* Helper for filter(): filter a tuple through a function */
2294 filtertuple(PyObject
*func
, PyObject
*tuple
)
2298 int len
= PyTuple_Size(tuple
);
2305 if ((result
= PyTuple_New(len
)) == NULL
)
2308 for (i
= j
= 0; i
< len
; ++i
) {
2309 PyObject
*item
, *good
;
2312 if ((item
= PyTuple_GetItem(tuple
, i
)) == NULL
)
2314 if (func
== Py_None
) {
2319 PyObject
*arg
= Py_BuildValue("(O)", item
);
2322 good
= PyEval_CallObject(func
, arg
);
2327 ok
= PyObject_IsTrue(good
);
2331 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2336 if (_PyTuple_Resize(&result
, j
, 0) < 0)
2347 /* Helper for filter(): filter a string through a function */
2350 filterstring(PyObject
*func
, PyObject
*strobj
)
2354 int len
= PyString_Size(strobj
);
2356 if (func
== Py_None
) {
2357 /* No character is ever false -- share input string */
2361 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2364 for (i
= j
= 0; i
< len
; ++i
) {
2365 PyObject
*item
, *arg
, *good
;
2368 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2371 arg
= Py_BuildValue("(O)", item
);
2375 good
= PyEval_CallObject(func
, arg
);
2379 ok
= PyObject_IsTrue(good
);
2382 PyString_AS_STRING((PyStringObject
*)result
)[j
++] =
2383 PyString_AS_STRING((PyStringObject
*)item
)[0];
2386 if (j
< len
&& _PyString_Resize(&result
, j
) < 0)