1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Built-in functions */
49 static PyObject
*filterstring
Py_PROTO((PyObject
*, PyObject
*));
50 static PyObject
*filtertuple
Py_PROTO((PyObject
*, PyObject
*));
53 builtin___import__(self
, args
)
58 PyObject
*globals
= NULL
;
59 PyObject
*locals
= NULL
;
60 PyObject
*fromlist
= NULL
;
62 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
63 &name
, &globals
, &locals
, &fromlist
))
65 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
68 static char import_doc
[] =
69 "__import__(name, globals, locals, fromlist) -> module\n\
71 Import a module. The globals are only used to determine the context;\n\
72 they are not modified. The locals are currently unused. The fromlist\n\
73 should be a list of names to emulate ``from name import ...'', or an\n\
74 empty list to emulate ``import name''.\n\
75 When importing a module from a package, note that __import__('A.B', ...)\n\
76 returns package A when fromlist is empty, but its submodule B when\n\
77 fromlist is not empty.";
81 builtin_abs(self
, args
)
87 if (!PyArg_ParseTuple(args
, "O:abs", &v
))
89 return PyNumber_Absolute(v
);
92 static char abs_doc
[] =
93 "abs(number) -> number\n\
95 Return the absolute value of the argument.";
99 builtin_apply(self
, args
)
103 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
104 PyObject
*t
= NULL
, *retval
= NULL
;
106 if (!PyArg_ParseTuple(args
, "O|OO:apply", &func
, &alist
, &kwdict
))
109 if (!PyTuple_Check(alist
)) {
110 if (!PySequence_Check(alist
)) {
111 PyErr_SetString(PyExc_TypeError
,
112 "apply() 2nd argument must be a sequence");
115 t
= PySequence_Tuple(alist
);
121 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
122 PyErr_SetString(PyExc_TypeError
,
123 "apply() 3rd argument must be dictionary");
126 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
132 static char apply_doc
[] =
133 "apply(object, args[, kwargs]) -> value\n\
135 Call a callable object with positional arguments taken from the tuple args,\n\
136 and keyword arguments taken from the optional dictionary kwargs.\n\
137 Note that classes are callable, as are instances with a __call__() method.";
141 builtin_buffer(self
, args
)
147 int size
= Py_END_OF_BUFFER
;
149 if ( !PyArg_ParseTuple(args
, "O|ii:buffer", &ob
, &offset
, &size
) )
151 return PyBuffer_FromObject(ob
, offset
, size
);
154 static char buffer_doc
[] =
155 "buffer(object [, offset[, size]]) -> object\n\
157 Creates a new buffer object which references the given object.\n\
158 The buffer will reference a slice of the target object from the\n\
159 start of the object (or at the specified offset). The slice will\n\
160 extend to the end of the target object (or with the specified size).";
164 builtin_unicode(self
, args
)
170 char *encoding
= NULL
;
173 if ( !PyArg_ParseTuple(args
, "s#|ss:unicode", &s
, &len
,
174 &encoding
, &errors
) )
176 return PyUnicode_Decode(s
, len
, encoding
, errors
);
179 static char unicode_doc
[] =
180 "unicode(string [, encoding[, errors]]) -> object\n\
182 Creates a new unicode object from the given encoded string.\n\
183 encoding defaults to 'utf-8' and errors, defining the error handling,\n\
188 builtin_callable(self
, args
)
194 if (!PyArg_ParseTuple(args
, "O:callable", &v
))
196 return PyInt_FromLong((long)PyCallable_Check(v
));
199 static char callable_doc
[] =
200 "callable(object) -> Boolean\n\
202 Return whether the object is callable (i.e., some kind of function).\n\
203 Note that classes are callable, as are instances with a __call__() method.";
207 builtin_filter(self
, args
)
211 PyObject
*func
, *seq
, *result
;
212 PySequenceMethods
*sqf
;
216 if (!PyArg_ParseTuple(args
, "OO:filter", &func
, &seq
))
219 if (PyString_Check(seq
)) {
220 PyObject
*r
= filterstring(func
, seq
);
224 if (PyTuple_Check(seq
)) {
225 PyObject
*r
= filtertuple(func
, seq
);
229 sqf
= seq
->ob_type
->tp_as_sequence
;
230 if (sqf
== NULL
|| sqf
->sq_length
== NULL
|| sqf
->sq_item
== NULL
) {
231 PyErr_SetString(PyExc_TypeError
,
232 "argument 2 to filter() must be a sequence type");
236 if ((len
= (*sqf
->sq_length
)(seq
)) < 0)
239 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
244 if ((result
= PyList_New(len
)) == NULL
)
248 for (i
= j
= 0; ; ++i
) {
249 PyObject
*item
, *good
;
252 if ((item
= (*sqf
->sq_item
)(seq
, i
)) == NULL
) {
253 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
260 if (func
== Py_None
) {
265 PyObject
*arg
= Py_BuildValue("(O)", item
);
268 good
= PyEval_CallObject(func
, arg
);
275 ok
= PyObject_IsTrue(good
);
279 if (PyList_SetItem(result
, j
++, item
) < 0)
283 int status
= PyList_Append(result
, item
);
295 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
306 static char filter_doc
[] =
307 "filter(function, sequence) -> list\n\
309 Return a list containing those items of sequence for which function(item)\n\
310 is true. If function is None, return a list of items that are true.";
314 builtin_chr(self
, args
)
321 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
323 if (x
< 0 || x
>= 256) {
324 PyErr_SetString(PyExc_ValueError
,
325 "chr() arg not in range(256)");
329 return PyString_FromStringAndSize(s
, 1);
332 static char chr_doc
[] =
333 "chr(i) -> character\n\
335 Return a string of one character with ordinal i; 0 <= i < 256.";
339 builtin_unichr(self
, args
)
346 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
348 if (x
< 0 || x
>= 65536) {
349 PyErr_SetString(PyExc_ValueError
,
350 "unichr() arg not in range(65536)");
353 s
[0] = (Py_UNICODE
)x
;
354 return PyUnicode_FromUnicode(s
, 1);
357 static char unichr_doc
[] =
358 "unichr(i) -> unicode character\n\
360 Return a unicode string of one character with ordinal i; 0 <= i < 65536.";
364 builtin_cmp(self
, args
)
371 if (!PyArg_ParseTuple(args
, "OO:cmp", &a
, &b
))
373 if (PyObject_Cmp(a
, b
, &c
) < 0)
375 return PyInt_FromLong((long)c
);
378 static char cmp_doc
[] =
379 "cmp(x, y) -> integer\n\
381 Return negative if x<y, zero if x==y, positive if x>y.";
385 builtin_coerce(self
, args
)
392 if (!PyArg_ParseTuple(args
, "OO:coerce", &v
, &w
))
394 if (PyNumber_Coerce(&v
, &w
) < 0)
396 res
= Py_BuildValue("(OO)", v
, w
);
402 static char coerce_doc
[] =
403 "coerce(x, y) -> None or (x1, y1)\n\
405 When x and y can be coerced to values of the same type, return a tuple\n\
406 containing the coerced values. When they can't be coerced, return None.";
410 builtin_compile(self
, args
)
419 if (!PyArg_ParseTuple(args
, "sss:compile", &str
, &filename
, &startstr
))
421 if (strcmp(startstr
, "exec") == 0)
422 start
= Py_file_input
;
423 else if (strcmp(startstr
, "eval") == 0)
424 start
= Py_eval_input
;
425 else if (strcmp(startstr
, "single") == 0)
426 start
= Py_single_input
;
428 PyErr_SetString(PyExc_ValueError
,
429 "compile() mode must be 'exec' or 'eval' or 'single'");
432 return Py_CompileString(str
, filename
, start
);
435 static char compile_doc
[] =
436 "compile(source, filename, mode) -> code object\n\
438 Compile the source string (a Python module, statement or expression)\n\
439 into a code object that can be executed by the exec statement or eval().\n\
440 The filename will be used for run-time error messages.\n\
441 The mode must be 'exec' to compile a module, 'single' to compile a\n\
442 single (interactive) statement, or 'eval' to compile an expression.";
445 #ifndef WITHOUT_COMPLEX
448 complex_from_string(v
)
451 extern double strtod
Py_PROTO((const char *, char **));
452 char *s
, *start
, *end
;
453 double x
=0.0, y
=0.0, z
;
454 int got_re
=0, got_im
=0, done
=0;
458 char buffer
[256]; /* For errors */
460 start
= s
= PyString_AS_STRING(v
);
462 /* position on first nonblank */
463 while (*s
&& isspace(Py_CHARMASK(*s
)))
466 PyErr_SetString(PyExc_ValueError
,
467 "empty string for complex()");
478 if (s
-start
!= PyString_GET_SIZE(v
)) {
481 "null byte in argument for complex()");
484 if(!done
) sw_error
=1;
491 if (done
) sw_error
=1;
493 if ( *s
=='\0'||*s
=='+'||*s
=='-' ||
494 isspace(Py_CHARMASK(*s
)) ) sw_error
=1;
499 if (got_im
|| done
) {
511 if (*s
!='+' && *s
!='-' )
516 if (isspace(Py_CHARMASK(*s
))) {
517 while (*s
&& isspace(Py_CHARMASK(*s
)))
526 (*s
=='.' || isdigit(Py_CHARMASK(*s
)));
527 if (done
||!digit_or_dot
) {
532 PyFPE_START_PROTECT("strtod", return 0)
533 z
= strtod(s
, &end
) ;
537 "float() out of range: %.150s", s
);
544 if (*s
=='J' || *s
=='j') {
553 /* accept a real part */
561 } /* end of switch */
563 } while (*s
!='\0' && !sw_error
);
566 PyErr_SetString(PyExc_ValueError
,
567 "malformed string for complex()");
571 return PyComplex_FromDoubles(x
,y
);
575 builtin_complex(self
, args
)
579 PyObject
*r
, *i
, *tmp
;
580 PyNumberMethods
*nbr
, *nbi
= NULL
;
585 if (!PyArg_ParseTuple(args
, "O|O:complex", &r
, &i
))
587 if (PyString_Check(r
))
588 return complex_from_string(r
);
589 if ((nbr
= r
->ob_type
->tp_as_number
) == NULL
||
590 nbr
->nb_float
== NULL
||
592 ((nbi
= i
->ob_type
->tp_as_number
) == NULL
||
593 nbi
->nb_float
== NULL
))) {
594 PyErr_SetString(PyExc_TypeError
,
595 "complex() argument can't be converted to complex");
598 /* XXX Hack to support classes with __complex__ method */
599 if (PyInstance_Check(r
)) {
600 static PyObject
*complexstr
;
602 if (complexstr
== NULL
) {
603 complexstr
= PyString_InternFromString("__complex__");
604 if (complexstr
== NULL
)
607 f
= PyObject_GetAttr(r
, complexstr
);
611 PyObject
*args
= Py_BuildValue("()");
614 r
= PyEval_CallObject(f
, args
);
622 if (PyComplex_Check(r
)) {
623 cr
= ((PyComplexObject
*)r
)->cval
;
629 tmp
= (*nbr
->nb_float
)(r
);
635 cr
.real
= PyFloat_AsDouble(tmp
);
643 else if (PyComplex_Check(i
))
644 ci
= ((PyComplexObject
*)i
)->cval
;
646 tmp
= (*nbi
->nb_float
)(i
);
649 ci
.real
= PyFloat_AsDouble(tmp
);
655 return PyComplex_FromCComplex(cr
);
658 static char complex_doc
[] =
659 "complex(real[, imag]) -> complex number\n\
661 Create a complex number from a real part and an optional imaginary part.\n\
662 This is equivalent to (real + imag*1j) where imag defaults to 0.";
668 builtin_dir(self
, args
)
672 static char *attrlist
[] = {"__members__", "__methods__", NULL
};
673 PyObject
*v
= NULL
, *l
= NULL
, *m
= NULL
;
678 if (!PyArg_ParseTuple(args
, "|O:dir", &v
))
681 x
= PyEval_GetLocals();
684 l
= PyMapping_Keys(x
);
689 d
= PyObject_GetAttrString(v
, "__dict__");
693 l
= PyMapping_Keys(d
);
703 for (s
= attrlist
; *s
!= NULL
; s
++) {
704 m
= PyObject_GetAttrString(v
, *s
);
710 x
= PySequence_GetItem(m
, i
);
715 if (PyList_Append(l
, x
) != 0) {
725 if (PyList_Sort(l
) != 0)
733 static char dir_doc
[] =
734 "dir([object]) -> list of strings\n\
736 Return an alphabetized list of names comprising (some of) the attributes\n\
737 of the given object. Without an argument, the names in the current scope\n\
738 are listed. With an instance argument, only the instance attributes are\n\
739 returned. With a class argument, attributes of the base class are not\n\
740 returned. For other types or arguments, this may list members or methods.";
744 builtin_divmod(self
, args
)
750 if (!PyArg_ParseTuple(args
, "OO:divmod", &v
, &w
))
752 return PyNumber_Divmod(v
, w
);
755 static char divmod_doc
[] =
756 "divmod(x, y) -> (div, mod)\n\
758 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
762 builtin_eval(self
, args
)
767 PyObject
*globals
= Py_None
, *locals
= Py_None
;
770 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
772 &PyDict_Type
, &globals
,
773 &PyDict_Type
, &locals
))
775 if (globals
== Py_None
) {
776 globals
= PyEval_GetGlobals();
777 if (locals
== Py_None
)
778 locals
= PyEval_GetLocals();
780 else if (locals
== Py_None
)
782 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
783 if (PyDict_SetItemString(globals
, "__builtins__",
784 PyEval_GetBuiltins()) != 0)
787 if (PyCode_Check(cmd
))
788 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
789 if (!PyString_Check(cmd
)) {
790 PyErr_SetString(PyExc_TypeError
,
791 "eval() argument 1 must be string or code object");
794 str
= PyString_AsString(cmd
);
795 if ((int)strlen(str
) != PyString_Size(cmd
)) {
796 PyErr_SetString(PyExc_ValueError
,
797 "embedded '\\0' in string arg");
800 while (*str
== ' ' || *str
== '\t')
802 return PyRun_String(str
, Py_eval_input
, globals
, locals
);
805 static char eval_doc
[] =
806 "eval(source[, globals[, locals]]) -> value\n\
808 Evaluate the source in the context of globals and locals.\n\
809 The source may be a string representing a Python expression\n\
810 or a code object as returned by compile().\n\
811 The globals and locals are dictionaries, defaulting to the current\n\
812 globals and locals. If only globals is given, locals defaults to it.";
816 builtin_execfile(self
, args
)
821 PyObject
*globals
= Py_None
, *locals
= Py_None
;
825 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
827 &PyDict_Type
, &globals
,
828 &PyDict_Type
, &locals
))
830 if (globals
== Py_None
) {
831 globals
= PyEval_GetGlobals();
832 if (locals
== Py_None
)
833 locals
= PyEval_GetLocals();
835 else if (locals
== Py_None
)
837 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
838 if (PyDict_SetItemString(globals
, "__builtins__",
839 PyEval_GetBuiltins()) != 0)
842 Py_BEGIN_ALLOW_THREADS
843 fp
= fopen(filename
, "r");
846 PyErr_SetFromErrno(PyExc_IOError
);
849 res
= PyRun_File(fp
, filename
, Py_file_input
, globals
, locals
);
850 Py_BEGIN_ALLOW_THREADS
856 static char execfile_doc
[] =
857 "execfile(filename[, globals[, locals]])\n\
859 Read and execute a Python script from a file.\n\
860 The globals and locals are dictionaries, defaulting to the current\n\
861 globals and locals. If only globals is given, locals defaults to it.";
865 builtin_getattr(self
, args
)
869 PyObject
*v
, *result
, *dflt
= NULL
;
872 if (!PyArg_ParseTuple(args
, "OS|O:getattr", &v
, &name
, &dflt
))
874 result
= PyObject_GetAttr(v
, name
);
875 if (result
== NULL
&& dflt
!= NULL
) {
883 static char getattr_doc
[] =
884 "getattr(object, name[, default]) -> value\n\
886 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
887 When a default argument is given, it is returned when the attribute doesn't\n\
888 exist; without it, an exception is raised in that case.";
892 builtin_globals(self
, args
)
898 if (!PyArg_ParseTuple(args
, ":globals"))
900 d
= PyEval_GetGlobals();
905 static char globals_doc
[] =
906 "globals() -> dictionary\n\
908 Return the dictionary containing the current scope's global variables.";
912 builtin_hasattr(self
, args
)
919 if (!PyArg_ParseTuple(args
, "OS:hasattr", &v
, &name
))
921 v
= PyObject_GetAttr(v
, name
);
932 static char hasattr_doc
[] =
933 "hasattr(object, name) -> Boolean\n\
935 Return whether the object has an attribute with the given name.\n\
936 (This is done by calling getattr(object, name) and catching exceptions.)";
940 builtin_id(self
, args
)
946 if (!PyArg_ParseTuple(args
, "O:id", &v
))
948 return PyInt_FromLong((long)v
);
951 static char id_doc
[] =
952 "id(object) -> integer\n\
954 Return the identity of an object. This is guaranteed to be unique among\n\
955 simultaneously existing objects. (Hint: it's the object's memory address.)";
959 builtin_map(self
, args
)
965 PySequenceMethods
*sqf
;
969 PyObject
*func
, *result
;
970 sequence
*seqs
= NULL
, *sqp
;
974 n
= PyTuple_Size(args
);
976 PyErr_SetString(PyExc_TypeError
,
977 "map() requires at least two args");
981 func
= PyTuple_GetItem(args
, 0);
984 if (func
== Py_None
&& n
== 1) {
985 /* map(None, S) is the same as list(S). */
986 return PySequence_List(PyTuple_GetItem(args
, 1));
989 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
994 for (len
= 0, i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
996 PySequenceMethods
*sqf
;
998 if ((sqp
->seq
= PyTuple_GetItem(args
, i
+ 1)) == NULL
)
1001 sqp
->sqf
= sqf
= sqp
->seq
->ob_type
->tp_as_sequence
;
1003 sqf
->sq_length
== NULL
||
1004 sqf
->sq_item
== NULL
)
1006 static char errmsg
[] =
1007 "argument %d to map() must be a sequence object";
1008 char errbuf
[sizeof(errmsg
) + 25];
1010 sprintf(errbuf
, errmsg
, i
+2);
1011 PyErr_SetString(PyExc_TypeError
, errbuf
);
1015 if ((curlen
= sqp
->len
= (*sqp
->sqf
->sq_length
)(sqp
->seq
)) < 0)
1022 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
1025 for (i
= 0; ; ++i
) {
1026 PyObject
*alist
, *item
=NULL
, *value
;
1029 if (func
== Py_None
&& n
== 1)
1032 if ((alist
= PyTuple_New(n
)) == NULL
)
1036 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
1042 item
= (*sqp
->sqf
->sq_item
)(sqp
->seq
, i
);
1044 if (PyErr_ExceptionMatches(
1062 if (PyTuple_SetItem(alist
, j
, item
) < 0) {
1081 if (func
== Py_None
)
1084 value
= PyEval_CallObject(func
, alist
);
1090 int status
= PyList_Append(result
, value
);
1096 if (PyList_SetItem(result
, i
, value
) < 0)
1101 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1110 if (seqs
) PyMem_DEL(seqs
);
1114 static char map_doc
[] =
1115 "map(function, sequence[, sequence, ...]) -> list\n\
1117 Return a list of the results of applying the function to the items of\n\
1118 the argument sequence(s). If more than one sequence is given, the\n\
1119 function is called with an argument list consisting of the corresponding\n\
1120 item of each sequence, substituting None for missing values when not all\n\
1121 sequences have the same length. If the function is None, return a list of\n\
1122 the items of the sequence (or a list of tuples if more than one sequence).";
1126 builtin_setattr(self
, args
)
1134 if (!PyArg_ParseTuple(args
, "OSO:setattr", &v
, &name
, &value
))
1136 if (PyObject_SetAttr(v
, name
, value
) != 0)
1142 static char setattr_doc
[] =
1143 "setattr(object, name, value)\n\
1145 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1150 builtin_delattr(self
, args
)
1157 if (!PyArg_ParseTuple(args
, "OS:delattr", &v
, &name
))
1159 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1165 static char delattr_doc
[] =
1166 "delattr(object, name)\n\
1168 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1173 builtin_hash(self
, args
)
1180 if (!PyArg_ParseTuple(args
, "O:hash", &v
))
1182 x
= PyObject_Hash(v
);
1185 return PyInt_FromLong(x
);
1188 static char hash_doc
[] =
1189 "hash(object) -> integer\n\
1191 Return a hash value for the object. Two objects with the same value have\n\
1192 the same hash value. The reverse is not necessarily true, but likely.";
1196 builtin_hex(self
, args
)
1201 PyNumberMethods
*nb
;
1203 if (!PyArg_ParseTuple(args
, "O:hex", &v
))
1206 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1207 nb
->nb_hex
== NULL
) {
1208 PyErr_SetString(PyExc_TypeError
,
1209 "hex() argument can't be converted to hex");
1212 return (*nb
->nb_hex
)(v
);
1215 static char hex_doc
[] =
1216 "hex(number) -> string\n\
1218 Return the hexadecimal representation of an integer or long integer.";
1221 static PyObject
*builtin_raw_input
Py_PROTO((PyObject
*, PyObject
*));
1224 builtin_input(self
, args
)
1231 PyObject
*globals
, *locals
;
1233 line
= builtin_raw_input(self
, args
);
1236 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1238 while (*str
== ' ' || *str
== '\t')
1240 globals
= PyEval_GetGlobals();
1241 locals
= PyEval_GetLocals();
1242 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1243 if (PyDict_SetItemString(globals
, "__builtins__",
1244 PyEval_GetBuiltins()) != 0)
1247 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
1252 static char input_doc
[] =
1253 "input([prompt]) -> value\n\
1255 Equivalent to eval(raw_input(prompt)).";
1259 builtin_intern(self
, args
)
1264 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1267 PyString_InternInPlace(&s
);
1271 static char intern_doc
[] =
1272 "intern(string) -> string\n\
1274 ``Intern'' the given string. This enters the string in the (global)\n\
1275 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1276 Return the string itself or the previously interned string object with the\n\
1281 builtin_int(self
, args
)
1286 int base
= -909; /* unlikely! */
1288 if (!PyArg_ParseTuple(args
, "O|i:int", &v
, &base
))
1291 return PyNumber_Int(v
);
1292 else if (!PyString_Check(v
)) {
1293 PyErr_SetString(PyExc_TypeError
,
1294 "can't convert non-string with explicit base");
1297 return PyInt_FromString(PyString_AS_STRING(v
), NULL
, base
);
1300 static char int_doc
[] =
1301 "int(x[, base]) -> integer\n\
1303 Convert a string or number to an integer, if possible. A floating point\n\
1304 argument will be truncated towards zero (this does not include a string\n\
1305 representation of a floating point number!) When converting a string, use\n\
1306 the optional base. It is an error to supply a base when converting a\n\
1311 builtin_long(self
, args
)
1316 int base
= -909; /* unlikely! */
1318 if (!PyArg_ParseTuple(args
, "O|i:long", &v
, &base
))
1321 return PyNumber_Long(v
);
1322 else if (!PyString_Check(v
)) {
1323 PyErr_SetString(PyExc_TypeError
,
1324 "can't convert non-string with explicit base");
1327 return PyLong_FromString(PyString_AS_STRING(v
), NULL
, base
);
1330 static char long_doc
[] =
1331 "long(x) -> long integer\n\
1332 long(x, base) -> long integer\n\
1334 Convert a string or number to a long integer, if possible. A floating\n\
1335 point argument will be truncated towards zero (this does not include a\n\
1336 string representation of a floating point number!) When converting a\n\
1337 string, use the given base. It is an error to supply a base when\n\
1338 converting a non-string.";
1342 builtin_float(self
, args
)
1348 if (!PyArg_ParseTuple(args
, "O:float", &v
))
1350 if (PyString_Check(v
))
1351 return PyFloat_FromString(v
, NULL
);
1352 return PyNumber_Float(v
);
1355 static char float_doc
[] =
1356 "float(x) -> floating point number\n\
1358 Convert a string or number to a floating point number, if possible.";
1362 builtin_len(self
, args
)
1369 if (!PyArg_ParseTuple(args
, "O:len", &v
))
1371 res
= PyObject_Length(v
);
1372 if (res
< 0 && PyErr_Occurred())
1374 return PyInt_FromLong(res
);
1377 static char len_doc
[] =
1378 "len(object) -> integer\n\
1380 Return the number of items of a sequence or mapping.";
1384 builtin_list(self
, args
)
1390 if (!PyArg_ParseTuple(args
, "O:list", &v
))
1392 return PySequence_List(v
);
1395 static char list_doc
[] =
1396 "list(sequence) -> list\n\
1398 Return a new list whose items are the same as those of the argument sequence.";
1402 builtin_slice(self
, args
)
1406 PyObject
*start
, *stop
, *step
;
1408 start
= stop
= step
= NULL
;
1410 if (!PyArg_ParseTuple(args
, "O|OO:slice", &start
, &stop
, &step
))
1413 /* This swapping of stop and start is to maintain similarity with
1419 return PySlice_New(start
, stop
, step
);
1422 static char slice_doc
[] =
1423 "slice([start,] stop[, step]) -> slice object\n\
1425 Create a slice object. This is used for slicing by the Numeric extensions.";
1429 builtin_locals(self
, args
)
1435 if (!PyArg_ParseTuple(args
, ":locals"))
1437 d
= PyEval_GetLocals();
1442 static char locals_doc
[] =
1443 "locals() -> dictionary\n\
1445 Return the dictionary containing the current scope's local variables.";
1454 PyObject
*v
, *w
, *x
;
1455 PySequenceMethods
*sq
;
1457 if (PyTuple_Size(args
) > 1)
1459 else if (!PyArg_ParseTuple(args
, "O:min/max", &v
))
1461 sq
= v
->ob_type
->tp_as_sequence
;
1462 if (sq
== NULL
|| sq
->sq_item
== NULL
) {
1463 PyErr_SetString(PyExc_TypeError
,
1464 "min() or max() of non-sequence");
1468 for (i
= 0; ; i
++) {
1469 x
= (*sq
->sq_item
)(v
, i
); /* Implies INCREF */
1471 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1481 int c
= PyObject_Compare(x
, w
);
1482 if (c
&& PyErr_Occurred()) {
1496 PyErr_SetString(PyExc_ValueError
,
1497 "min() or max() of empty sequence");
1502 builtin_min(self
, v
)
1506 return min_max(v
, -1);
1509 static char min_doc
[] =
1510 "min(sequence) -> value\n\
1511 min(a, b, c, ...) -> value\n\
1513 With a single sequence argument, return its smallest item.\n\
1514 With two or more arguments, return the smallest argument.";
1518 builtin_max(self
, v
)
1522 return min_max(v
, 1);
1525 static char max_doc
[] =
1526 "max(sequence) -> value\n\
1527 max(a, b, c, ...) -> value\n\
1529 With a single sequence argument, return its largest item.\n\
1530 With two or more arguments, return the largest argument.";
1534 builtin_oct(self
, args
)
1539 PyNumberMethods
*nb
;
1541 if (!PyArg_ParseTuple(args
, "O:oct", &v
))
1543 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1544 nb
->nb_oct
== NULL
) {
1545 PyErr_SetString(PyExc_TypeError
,
1546 "oct() argument can't be converted to oct");
1549 return (*nb
->nb_oct
)(v
);
1552 static char oct_doc
[] =
1553 "oct(number) -> string\n\
1555 Return the octal representation of an integer or long integer.";
1559 builtin_open(self
, args
)
1568 if (!PyArg_ParseTuple(args
, "s|si:open", &name
, &mode
, &bufsize
))
1570 f
= PyFile_FromString(name
, mode
);
1572 PyFile_SetBufSize(f
, bufsize
);
1576 static char open_doc
[] =
1577 "open(filename[, mode[, buffering]]) -> file object\n\
1579 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1580 writing or appending. The file will be created if it doesn't exist\n\
1581 when opened for writing or appending; it will be truncated when\n\
1582 opened for writing. Add a 'b' to the mode for binary files.\n\
1583 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1584 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1585 buffered, and larger numbers specify the buffer size.";
1589 builtin_ord(self
, args
)
1596 if (!PyArg_ParseTuple(args
, "O:ord", &obj
))
1599 if (PyString_Check(obj
) && PyString_GET_SIZE(obj
) == 1)
1600 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1601 else if (PyUnicode_Check(obj
) && PyUnicode_GET_SIZE(obj
) == 1)
1602 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1604 PyErr_SetString(PyExc_TypeError
,
1605 "expected a string or unicode character");
1609 return PyInt_FromLong(ord
);
1612 static char ord_doc
[] =
1613 "ord(c) -> integer\n\
1615 Return the integer ordinal of a one character [unicode] string.";
1619 builtin_pow(self
, args
)
1623 PyObject
*v
, *w
, *z
= Py_None
;
1625 if (!PyArg_ParseTuple(args
, "OO|O:pow", &v
, &w
, &z
))
1627 return PyNumber_Power(v
, w
, z
);
1630 static char pow_doc
[] =
1631 "pow(x, y[, z]) -> number\n\
1633 With two arguments, equivalent to x**y. With three arguments,\n\
1634 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1637 /* Return number of items in range/xrange (lo, hi, step). step > 0
1638 * required. Return a value < 0 if & only if the true value is too
1639 * large to fit in a signed long.
1642 get_len_of_range(lo
, hi
, step
)
1645 long step
; /* must be > 0 */
1647 /* -------------------------------------------------------------
1648 If lo >= hi, the range is empty.
1649 Else if n values are in the range, the last one is
1650 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1651 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1652 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1653 the RHS is non-negative and so truncation is the same as the
1654 floor. Letting M be the largest positive long, the worst case
1655 for the RHS numerator is hi=M, lo=-M-1, and then
1656 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1657 precision to compute the RHS exactly.
1658 ---------------------------------------------------------------*/
1661 unsigned long uhi
= (unsigned long)hi
;
1662 unsigned long ulo
= (unsigned long)lo
;
1663 unsigned long diff
= uhi
- ulo
- 1;
1664 n
= (long)(diff
/ (unsigned long)step
+ 1);
1670 builtin_range(self
, args
)
1674 long ilow
= 0, ihigh
= 0, istep
= 1;
1680 if (PyTuple_Size(args
) <= 1) {
1681 if (!PyArg_ParseTuple(args
,
1682 "l;range() requires 1-3 int arguments",
1687 if (!PyArg_ParseTuple(args
,
1688 "ll|l;range() requires 1-3 int arguments",
1689 &ilow
, &ihigh
, &istep
))
1693 PyErr_SetString(PyExc_ValueError
, "zero step for range()");
1697 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1699 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1701 if (bign
< 0 || (long)n
!= bign
) {
1702 PyErr_SetString(PyExc_OverflowError
,
1703 "range() has too many items");
1709 for (i
= 0; i
< n
; i
++) {
1710 PyObject
*w
= PyInt_FromLong(ilow
);
1715 PyList_SET_ITEM(v
, i
, w
);
1721 static char range_doc
[] =
1722 "range([start,] stop[, step]) -> list of integers\n\
1724 Return a list containing an arithmetic progression of integers.\n\
1725 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1726 When step is given, it specifies the increment (or decrement).\n\
1727 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1728 These are exactly the valid indices for a list of 4 elements.";
1732 builtin_xrange(self
, args
)
1736 long ilow
= 0, ihigh
= 0, istep
= 1;
1739 if (PyTuple_Size(args
) <= 1) {
1740 if (!PyArg_ParseTuple(args
,
1741 "l;xrange() requires 1-3 int arguments",
1746 if (!PyArg_ParseTuple(args
,
1747 "ll|l;xrange() requires 1-3 int arguments",
1748 &ilow
, &ihigh
, &istep
))
1752 PyErr_SetString(PyExc_ValueError
, "zero step for xrange()");
1756 n
= get_len_of_range(ilow
, ihigh
, istep
);
1758 n
= get_len_of_range(ihigh
, ilow
, -istep
);
1760 PyErr_SetString(PyExc_OverflowError
,
1761 "xrange() has more than sys.maxint items");
1764 return PyRange_New(ilow
, n
, istep
, 1);
1767 static char xrange_doc
[] =
1768 "xrange([start,] stop[, step]) -> xrange object\n\
1770 Like range(), but instead of returning a list, returns an object that\n\
1771 generates the numbers in the range on demand. This is slightly slower\n\
1772 than range() but more memory efficient.";
1776 builtin_raw_input(self
, args
)
1783 if (!PyArg_ParseTuple(args
, "|O:[raw_]input", &v
))
1785 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin
&&
1786 PyFile_AsFile(PySys_GetObject("stdout")) == stdout
&&
1787 isatty(fileno(stdin
)) && isatty(fileno(stdout
))) {
1793 po
= PyObject_Str(v
);
1796 prompt
= PyString_AsString(po
);
1804 s
= PyOS_Readline(prompt
);
1807 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1811 PyErr_SetNone(PyExc_EOFError
);
1814 else { /* strip trailing '\n' */
1815 result
= PyString_FromStringAndSize(s
, strlen(s
)-1);
1821 f
= PySys_GetObject("stdout");
1823 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
1826 if (Py_FlushLine() != 0 ||
1827 PyFile_WriteObject(v
, f
, Py_PRINT_RAW
) != 0)
1830 f
= PySys_GetObject("stdin");
1832 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdin");
1835 return PyFile_GetLine(f
, -1);
1838 static char raw_input_doc
[] =
1839 "raw_input([prompt]) -> string\n\
1841 Read a string from standard input. The trailing newline is stripped.\n\
1842 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1843 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1844 is printed without a trailing newline before reading.";
1848 builtin_reduce(self
, args
)
1852 PyObject
*seq
, *func
, *result
= NULL
;
1853 PySequenceMethods
*sqf
;
1856 if (!PyArg_ParseTuple(args
, "OO|O:reduce", &func
, &seq
, &result
))
1861 sqf
= seq
->ob_type
->tp_as_sequence
;
1862 if (sqf
== NULL
|| sqf
->sq_item
== NULL
) {
1863 PyErr_SetString(PyExc_TypeError
,
1864 "2nd argument to reduce() must be a sequence object");
1868 if ((args
= PyTuple_New(2)) == NULL
)
1871 for (i
= 0; ; ++i
) {
1874 if (args
->ob_refcnt
> 1) {
1876 if ((args
= PyTuple_New(2)) == NULL
)
1880 if ((op2
= (*sqf
->sq_item
)(seq
, i
)) == NULL
) {
1881 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1891 PyTuple_SetItem(args
, 0, result
);
1892 PyTuple_SetItem(args
, 1, op2
);
1893 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1901 PyErr_SetString(PyExc_TypeError
,
1902 "reduce of empty sequence with no initial value");
1912 static char reduce_doc
[] =
1913 "reduce(function, sequence[, initial]) -> value\n\
1915 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1916 from left to right, so as to reduce the sequence to a single value.\n\
1917 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1918 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1919 of the sequence in the calculation, and serves as a default when the\n\
1920 sequence is empty.";
1924 builtin_reload(self
, args
)
1930 if (!PyArg_ParseTuple(args
, "O:reload", &v
))
1932 return PyImport_ReloadModule(v
);
1935 static char reload_doc
[] =
1936 "reload(module) -> module\n\
1938 Reload the module. The module must have been successfully imported before.";
1942 builtin_repr(self
, args
)
1948 if (!PyArg_ParseTuple(args
, "O:repr", &v
))
1950 return PyObject_Repr(v
);
1953 static char repr_doc
[] =
1954 "repr(object) -> string\n\
1956 Return the canonical string representation of the object.\n\
1957 For most object types, eval(repr(object)) == object.";
1961 builtin_round(self
, args
)
1970 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1988 return PyFloat_FromDouble(x
);
1991 static char round_doc
[] =
1992 "round(number[, ndigits]) -> floating point number\n\
1994 Round a number to a given precision in decimal digits (default 0 digits).\n\
1995 This always returns a floating point number. Precision may be negative.";
1999 builtin_str(self
, args
)
2005 if (!PyArg_ParseTuple(args
, "O:str", &v
))
2007 return PyObject_Str(v
);
2010 static char str_doc
[] =
2011 "str(object) -> string\n\
2013 Return a nice string representation of the object.\n\
2014 If the argument is a string, the return value is the same object.";
2018 builtin_tuple(self
, args
)
2024 if (!PyArg_ParseTuple(args
, "O:tuple", &v
))
2026 return PySequence_Tuple(v
);
2029 static char tuple_doc
[] =
2030 "tuple(sequence) -> list\n\
2032 Return a tuple whose items are the same as those of the argument sequence.\n\
2033 If the argument is a tuple, the return value is the same object.";
2037 builtin_type(self
, args
)
2043 if (!PyArg_ParseTuple(args
, "O:type", &v
))
2045 v
= (PyObject
*)v
->ob_type
;
2050 static char type_doc
[] =
2051 "type(object) -> type object\n\
2053 Return the type of the object.";
2057 builtin_vars(self
, args
)
2064 if (!PyArg_ParseTuple(args
, "|O:vars", &v
))
2067 d
= PyEval_GetLocals();
2069 if (!PyErr_Occurred())
2070 PyErr_SetString(PyExc_SystemError
,
2077 d
= PyObject_GetAttrString(v
, "__dict__");
2079 PyErr_SetString(PyExc_TypeError
,
2080 "vars() argument must have __dict__ attribute");
2087 static char vars_doc
[] =
2088 "vars([object]) -> dictionary\n\
2090 Without arguments, equivalent to locals().\n\
2091 With an argument, equivalent to object.__dict__.";
2094 abstract_issubclass(derived
, cls
, err
, first
)
2100 static PyObject
*__bases__
= NULL
;
2105 if (__bases__
== NULL
) {
2106 __bases__
= PyString_FromString("__bases__");
2107 if (__bases__
== NULL
)
2112 bases
= PyObject_GetAttr(cls
, __bases__
);
2113 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
2115 PyErr_SetString(PyExc_TypeError
, err
);
2124 bases
= PyObject_GetAttr(derived
, __bases__
);
2125 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
2127 PyErr_SetString(PyExc_TypeError
, err
);
2131 n
= PyTuple_GET_SIZE(bases
);
2132 for (i
= 0; i
< n
; i
++) {
2133 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
),
2145 builtin_isinstance(self
, args
)
2152 static PyObject
*__class__
= NULL
;
2155 if (!PyArg_ParseTuple(args
, "OO:isinstance", &inst
, &cls
))
2158 if (PyClass_Check(cls
)) {
2159 if (PyInstance_Check(inst
)) {
2161 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2162 retval
= PyClass_IsSubclass(inclass
, cls
);
2165 else if (PyType_Check(cls
)) {
2166 retval
= ((PyObject
*)(inst
->ob_type
) == cls
);
2168 else if (!PyInstance_Check(inst
)) {
2169 if (__class__
== NULL
) {
2170 __class__
= PyString_FromString("__class__");
2171 if (__class__
== NULL
)
2174 icls
= PyObject_GetAttr(inst
, __class__
);
2176 retval
= abstract_issubclass(
2178 "second argument must be a class",
2185 PyErr_SetString(PyExc_TypeError
,
2186 "second argument must be a class");
2191 PyErr_SetString(PyExc_TypeError
,
2192 "second argument must be a class");
2195 return PyInt_FromLong(retval
);
2198 static char isinstance_doc
[] =
2199 "isinstance(object, class-or-type) -> Boolean\n\
2201 Return whether an object is an instance of a class or of a subclass thereof.\n\
2202 With a type as second argument, return whether that is the object's type.";
2206 builtin_issubclass(self
, args
)
2214 if (!PyArg_ParseTuple(args
, "OO:issubclass", &derived
, &cls
))
2217 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2218 retval
= abstract_issubclass(
2219 derived
, cls
, "arguments must be classes", 1);
2225 if (!(retval
= (derived
== cls
)))
2226 retval
= PyClass_IsSubclass(derived
, cls
);
2229 return PyInt_FromLong(retval
);
2232 static char issubclass_doc
[] =
2233 "issubclass(C, B) -> Boolean\n\
2235 Return whether class C is a subclass (i.e., a derived class) of class B.";
2238 static PyMethodDef builtin_methods
[] = {
2239 {"__import__", builtin___import__
, 1, import_doc
},
2240 {"abs", builtin_abs
, 1, abs_doc
},
2241 {"apply", builtin_apply
, 1, apply_doc
},
2242 {"buffer", builtin_buffer
, 1, buffer_doc
},
2243 {"callable", builtin_callable
, 1, callable_doc
},
2244 {"chr", builtin_chr
, 1, chr_doc
},
2245 {"cmp", builtin_cmp
, 1, cmp_doc
},
2246 {"coerce", builtin_coerce
, 1, coerce_doc
},
2247 {"compile", builtin_compile
, 1, compile_doc
},
2248 #ifndef WITHOUT_COMPLEX
2249 {"complex", builtin_complex
, 1, complex_doc
},
2251 {"delattr", builtin_delattr
, 1, delattr_doc
},
2252 {"dir", builtin_dir
, 1, dir_doc
},
2253 {"divmod", builtin_divmod
, 1, divmod_doc
},
2254 {"eval", builtin_eval
, 1, eval_doc
},
2255 {"execfile", builtin_execfile
, 1, execfile_doc
},
2256 {"filter", builtin_filter
, 1, filter_doc
},
2257 {"float", builtin_float
, 1, float_doc
},
2258 {"getattr", builtin_getattr
, 1, getattr_doc
},
2259 {"globals", builtin_globals
, 1, globals_doc
},
2260 {"hasattr", builtin_hasattr
, 1, hasattr_doc
},
2261 {"hash", builtin_hash
, 1, hash_doc
},
2262 {"hex", builtin_hex
, 1, hex_doc
},
2263 {"id", builtin_id
, 1, id_doc
},
2264 {"input", builtin_input
, 1, input_doc
},
2265 {"intern", builtin_intern
, 1, intern_doc
},
2266 {"int", builtin_int
, 1, int_doc
},
2267 {"isinstance", builtin_isinstance
, 1, isinstance_doc
},
2268 {"issubclass", builtin_issubclass
, 1, issubclass_doc
},
2269 {"len", builtin_len
, 1, len_doc
},
2270 {"list", builtin_list
, 1, list_doc
},
2271 {"locals", builtin_locals
, 1, locals_doc
},
2272 {"long", builtin_long
, 1, long_doc
},
2273 {"map", builtin_map
, 1, map_doc
},
2274 {"max", builtin_max
, 1, max_doc
},
2275 {"min", builtin_min
, 1, min_doc
},
2276 {"oct", builtin_oct
, 1, oct_doc
},
2277 {"open", builtin_open
, 1, open_doc
},
2278 {"ord", builtin_ord
, 1, ord_doc
},
2279 {"pow", builtin_pow
, 1, pow_doc
},
2280 {"range", builtin_range
, 1, range_doc
},
2281 {"raw_input", builtin_raw_input
, 1, raw_input_doc
},
2282 {"reduce", builtin_reduce
, 1, reduce_doc
},
2283 {"reload", builtin_reload
, 1, reload_doc
},
2284 {"repr", builtin_repr
, 1, repr_doc
},
2285 {"round", builtin_round
, 1, round_doc
},
2286 {"setattr", builtin_setattr
, 1, setattr_doc
},
2287 {"slice", builtin_slice
, 1, slice_doc
},
2288 {"str", builtin_str
, 1, str_doc
},
2289 {"tuple", builtin_tuple
, 1, tuple_doc
},
2290 {"type", builtin_type
, 1, type_doc
},
2291 {"unicode", builtin_unicode
, 1, unicode_doc
},
2292 {"unichr", builtin_unichr
, 1, unichr_doc
},
2293 {"vars", builtin_vars
, 1, vars_doc
},
2294 {"xrange", builtin_xrange
, 1, xrange_doc
},
2298 /* Predefined exceptions */
2300 PyObject
*PyExc_Exception
;
2301 PyObject
*PyExc_StandardError
;
2302 PyObject
*PyExc_ArithmeticError
;
2303 PyObject
*PyExc_LookupError
;
2305 PyObject
*PyExc_AssertionError
;
2306 PyObject
*PyExc_AttributeError
;
2307 PyObject
*PyExc_EOFError
;
2308 PyObject
*PyExc_FloatingPointError
;
2309 PyObject
*PyExc_EnvironmentError
;
2310 PyObject
*PyExc_IOError
;
2311 PyObject
*PyExc_OSError
;
2312 PyObject
*PyExc_ImportError
;
2313 PyObject
*PyExc_IndexError
;
2314 PyObject
*PyExc_KeyError
;
2315 PyObject
*PyExc_KeyboardInterrupt
;
2316 PyObject
*PyExc_MemoryError
;
2317 PyObject
*PyExc_NameError
;
2318 PyObject
*PyExc_OverflowError
;
2319 PyObject
*PyExc_RuntimeError
;
2320 PyObject
*PyExc_NotImplementedError
;
2321 PyObject
*PyExc_SyntaxError
;
2322 PyObject
*PyExc_SystemError
;
2323 PyObject
*PyExc_SystemExit
;
2324 PyObject
*PyExc_UnboundLocalError
;
2325 PyObject
*PyExc_UnicodeError
;
2326 PyObject
*PyExc_TypeError
;
2327 PyObject
*PyExc_ValueError
;
2328 PyObject
*PyExc_ZeroDivisionError
;
2330 PyObject
*PyExc_WindowsError
;
2333 PyObject
*PyExc_MemoryErrorInst
;
2342 {"Exception", &PyExc_Exception
, 0},
2343 {"StandardError", &PyExc_StandardError
, 0},
2344 {"ArithmeticError", &PyExc_ArithmeticError
, 0},
2345 {"LookupError", &PyExc_LookupError
, 0},
2346 {"AssertionError", &PyExc_AssertionError
, 1},
2347 {"AttributeError", &PyExc_AttributeError
, 1},
2348 {"EOFError", &PyExc_EOFError
, 1},
2349 {"FloatingPointError", &PyExc_FloatingPointError
, 1},
2350 {"EnvironmentError", &PyExc_EnvironmentError
, 0},
2351 {"IOError", &PyExc_IOError
, 1},
2352 {"OSError", &PyExc_OSError
, 1},
2353 {"ImportError", &PyExc_ImportError
, 1},
2354 {"IndexError", &PyExc_IndexError
, 1},
2355 {"KeyError", &PyExc_KeyError
, 1},
2356 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt
, 1},
2357 {"MemoryError", &PyExc_MemoryError
, 1},
2358 /* Note: NameError is not a leaf in exceptions.py, but unlike
2359 the other non-leafs NameError is meant to be raised directly
2360 at times -- the leaf_exc member really seems to mean something
2361 like "this is an abstract base class" when false.
2363 {"NameError", &PyExc_NameError
, 1},
2364 {"OverflowError", &PyExc_OverflowError
, 1},
2365 {"RuntimeError", &PyExc_RuntimeError
, 1},
2366 {"NotImplementedError",&PyExc_NotImplementedError
,1},
2367 {"SyntaxError", &PyExc_SyntaxError
, 1},
2368 {"SystemError", &PyExc_SystemError
, 1},
2369 {"SystemExit", &PyExc_SystemExit
, 1},
2370 {"UnboundLocalError", &PyExc_UnboundLocalError
, 1},
2371 {"UnicodeError", &PyExc_UnicodeError
, 1},
2372 {"TypeError", &PyExc_TypeError
, 1},
2373 {"ValueError", &PyExc_ValueError
, 1},
2375 {"WindowsError", &PyExc_WindowsError
, 1},
2377 {"ZeroDivisionError", &PyExc_ZeroDivisionError
, 1},
2382 /* import exceptions module to extract class exceptions. on success,
2383 * return 1. on failure return 0 which signals _PyBuiltin_Init_2 to fall
2384 * back to using old-style string based exceptions.
2387 init_class_exc(dict
)
2391 PyObject
*m
= PyImport_ImportModule("exceptions");
2392 PyObject
*args
= NULL
;
2395 /* make sure we got the module and its dictionary */
2397 (d
= PyModule_GetDict(m
)) == NULL
)
2399 PySys_WriteStderr("'import exceptions' failed; ");
2400 if (Py_VerboseFlag
) {
2401 PySys_WriteStderr("traceback:\n");
2405 PySys_WriteStderr("use -v for traceback\n");
2409 for (i
= 0; bltin_exc
[i
].name
; i
++) {
2410 /* dig the exception out of the module */
2411 PyObject
*exc
= PyDict_GetItemString(d
, bltin_exc
[i
].name
);
2414 "Built-in exception class not found: %s. Library mismatch?\n",
2418 /* free the old-style exception string object */
2419 Py_XDECREF(*bltin_exc
[i
].exc
);
2421 /* squirrel away a pointer to the exception */
2423 *bltin_exc
[i
].exc
= exc
;
2425 /* and insert the name in the __builtin__ module */
2426 if (PyDict_SetItemString(dict
, bltin_exc
[i
].name
, exc
)) {
2428 "Cannot insert exception into __builtin__: %s\n",
2434 /* we need one pre-allocated instance */
2435 args
= Py_BuildValue("()");
2437 !(PyExc_MemoryErrorInst
=
2438 PyEval_CallObject(PyExc_MemoryError
, args
)))
2440 PySys_WriteStderr("Cannot pre-allocate MemoryError instance\n");
2445 /* we're done with the exceptions module */
2448 if (PyErr_Occurred()) {
2449 PySys_WriteStderr("Cannot initialize standard class exceptions; ");
2450 if (Py_VerboseFlag
) {
2451 PySys_WriteStderr("traceback:\n");
2455 PySys_WriteStderr("use -v for traceback\n");
2470 Py_XDECREF(PyExc_MemoryErrorInst
);
2471 PyExc_MemoryErrorInst
= NULL
;
2476 newstdexception(dict
, name
)
2480 PyObject
*v
= PyString_FromString(name
);
2481 if (v
== NULL
|| PyDict_SetItemString(dict
, name
, v
) != 0)
2482 Py_FatalError("Cannot create string-based exceptions");
2492 for (i
= 0; bltin_exc
[i
].name
; i
++, exccnt
++) {
2493 Py_XDECREF(*bltin_exc
[i
].exc
);
2494 if (bltin_exc
[i
].leaf_exc
)
2496 newstdexception(dict
, bltin_exc
[i
].name
);
2499 /* This is kind of bogus because we special case the some of the
2500 * new exceptions to be nearly forward compatible. But this means
2501 * we hard code knowledge about exceptions.py into C here. I don't
2502 * have a better solution, though.
2504 PyExc_LookupError
= PyTuple_New(2);
2505 Py_INCREF(PyExc_IndexError
);
2506 PyTuple_SET_ITEM(PyExc_LookupError
, 0, PyExc_IndexError
);
2507 Py_INCREF(PyExc_KeyError
);
2508 PyTuple_SET_ITEM(PyExc_LookupError
, 1, PyExc_KeyError
);
2509 PyDict_SetItemString(dict
, "LookupError", PyExc_LookupError
);
2511 PyExc_ArithmeticError
= PyTuple_New(3);
2512 Py_INCREF(PyExc_OverflowError
);
2513 PyTuple_SET_ITEM(PyExc_ArithmeticError
, 0, PyExc_OverflowError
);
2514 Py_INCREF(PyExc_ZeroDivisionError
);
2515 PyTuple_SET_ITEM(PyExc_ArithmeticError
, 1, PyExc_ZeroDivisionError
);
2516 Py_INCREF(PyExc_FloatingPointError
);
2517 PyTuple_SET_ITEM(PyExc_ArithmeticError
, 2, PyExc_FloatingPointError
);
2518 PyDict_SetItemString(dict
, "ArithmeticError", PyExc_ArithmeticError
);
2520 PyExc_EnvironmentError
= PyTuple_New(2);
2521 Py_INCREF(PyExc_IOError
);
2522 PyTuple_SET_ITEM(PyExc_EnvironmentError
, 0, PyExc_IOError
);
2523 Py_INCREF(PyExc_OSError
);
2524 PyTuple_SET_ITEM(PyExc_EnvironmentError
, 1, PyExc_OSError
);
2525 PyDict_SetItemString(dict
, "EnvironmentError", PyExc_EnvironmentError
);
2527 /* Make UnboundLocalError an alias for NameError */
2528 Py_INCREF(PyExc_NameError
);
2529 Py_DECREF(PyExc_UnboundLocalError
);
2530 PyExc_UnboundLocalError
= PyExc_NameError
;
2531 if (PyDict_SetItemString(dict
, "UnboundLocalError",
2532 PyExc_NameError
) != 0)
2533 Py_FatalError("Cannot create string-based exceptions");
2535 /* Make UnicodeError an alias for ValueError */
2536 Py_INCREF(PyExc_ValueError
);
2537 Py_DECREF(PyExc_UnicodeError
);
2538 PyExc_UnicodeError
= PyExc_ValueError
;
2539 if (PyDict_SetItemString(dict
, "UnicodeError",
2540 PyExc_ValueError
) != 0)
2541 Py_FatalError("Cannot create string-based exceptions");
2543 /* missing from the StandardError tuple: Exception, StandardError,
2546 PyExc_StandardError
= PyTuple_New(exccnt
-3);
2547 for (i
= 2, j
= 0; bltin_exc
[i
].name
; i
++) {
2548 PyObject
*exc
= *bltin_exc
[i
].exc
;
2549 /* SystemExit is not an error, but it is an exception */
2550 if (exc
!= PyExc_SystemExit
) {
2552 PyTuple_SET_ITEM(PyExc_StandardError
, j
++, exc
);
2555 PyDict_SetItemString(dict
, "StandardError", PyExc_StandardError
);
2557 /* Exception is a 2-tuple */
2558 PyExc_Exception
= PyTuple_New(2);
2559 Py_INCREF(PyExc_SystemExit
);
2560 PyTuple_SET_ITEM(PyExc_Exception
, 0, PyExc_SystemExit
);
2561 Py_INCREF(PyExc_StandardError
);
2562 PyTuple_SET_ITEM(PyExc_Exception
, 1, PyExc_StandardError
);
2563 PyDict_SetItemString(dict
, "Exception", PyExc_Exception
);
2565 if (PyErr_Occurred())
2566 Py_FatalError("Could not initialize built-in string exceptions");
2574 for (i
= 0; bltin_exc
[i
].name
; i
++) {
2575 PyObject
*exc
= *bltin_exc
[i
].exc
;
2577 *bltin_exc
[i
].exc
= NULL
;
2581 static char builtin_doc
[] =
2582 "Built-in functions, exceptions, and other objects.\n\
2584 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2589 PyObject
*mod
, *dict
;
2590 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2591 builtin_doc
, (PyObject
*)NULL
,
2592 PYTHON_API_VERSION
);
2595 dict
= PyModule_GetDict(mod
);
2597 if (PyDict_SetItemString(dict
, "None", Py_None
) < 0)
2599 if (PyDict_SetItemString(dict
, "Ellipsis", Py_Ellipsis
) < 0)
2601 if (PyDict_SetItemString(dict
, "__debug__",
2602 PyInt_FromLong(Py_OptimizeFlag
== 0)) < 0)
2609 _PyBuiltin_Init_2(dict
)
2612 /* if Python was started with -X, initialize the class exceptions */
2613 if (Py_UseClassExceptionsFlag
) {
2614 if (!init_class_exc(dict
)) {
2615 /* class based exceptions could not be
2616 * initialized. Fall back to using string based
2620 "Warning! Falling back to string-based exceptions\n");
2641 /* Helper for filter(): filter a tuple through a function */
2644 filtertuple(func
, tuple
)
2650 int len
= PyTuple_Size(tuple
);
2657 if ((result
= PyTuple_New(len
)) == NULL
)
2660 for (i
= j
= 0; i
< len
; ++i
) {
2661 PyObject
*item
, *good
;
2664 if ((item
= PyTuple_GetItem(tuple
, i
)) == NULL
)
2666 if (func
== Py_None
) {
2671 PyObject
*arg
= Py_BuildValue("(O)", item
);
2674 good
= PyEval_CallObject(func
, arg
);
2679 ok
= PyObject_IsTrue(good
);
2683 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2688 if (_PyTuple_Resize(&result
, j
, 0) < 0)
2699 /* Helper for filter(): filter a string through a function */
2702 filterstring(func
, strobj
)
2708 int len
= PyString_Size(strobj
);
2710 if (func
== Py_None
) {
2711 /* No character is ever false -- share input string */
2715 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2718 for (i
= j
= 0; i
< len
; ++i
) {
2719 PyObject
*item
, *arg
, *good
;
2722 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2725 arg
= Py_BuildValue("(O)", item
);
2729 good
= PyEval_CallObject(func
, arg
);
2733 ok
= PyObject_IsTrue(good
);
2736 PyString_AS_STRING((PyStringObject
*)result
)[j
++] =
2737 PyString_AS_STRING((PyStringObject
*)item
)[0];
2740 if (j
< len
&& _PyString_Resize(&result
, j
) < 0)