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(function, args[, kwargs]) -> value\n\
135 Call a function with positional arguments taken from the tuple args,\n\
136 and keyword arguments taken from the optional dictionary kwargs.";
140 builtin_buffer(self
, args
)
146 int size
= Py_END_OF_BUFFER
;
148 if ( !PyArg_ParseTuple(args
, "O|ii:buffer", &ob
, &offset
, &size
) )
150 return PyBuffer_FromObject(ob
, offset
, size
);
153 static char buffer_doc
[] =
154 "buffer(object [, offset[, size]) -> object\n\
156 Creates a new buffer object which references the given object.\n\
157 The buffer will reference a slice of the target object from the\n\
158 start of the object (or at the specified offset). The slice will\n\
159 extend to the end of the target object (or with the specified size).";
163 builtin_callable(self
, args
)
169 if (!PyArg_ParseTuple(args
, "O:callable", &v
))
171 return PyInt_FromLong((long)PyCallable_Check(v
));
174 static char callable_doc
[] =
175 "callable(object) -> Boolean\n\
177 Return whether the object is callable (i.e., some kind of function).\n\
178 Note that classes are callable, as are instances with a __call__() method.";
182 builtin_filter(self
, args
)
186 PyObject
*func
, *seq
, *result
;
187 PySequenceMethods
*sqf
;
191 if (!PyArg_ParseTuple(args
, "OO:filter", &func
, &seq
))
194 if (PyString_Check(seq
)) {
195 PyObject
*r
= filterstring(func
, seq
);
199 if (PyTuple_Check(seq
)) {
200 PyObject
*r
= filtertuple(func
, seq
);
204 sqf
= seq
->ob_type
->tp_as_sequence
;
205 if (sqf
== NULL
|| sqf
->sq_length
== NULL
|| sqf
->sq_item
== NULL
) {
206 PyErr_SetString(PyExc_TypeError
,
207 "argument 2 to filter() must be a sequence type");
211 if ((len
= (*sqf
->sq_length
)(seq
)) < 0)
214 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
219 if ((result
= PyList_New(len
)) == NULL
)
223 for (i
= j
= 0; ; ++i
) {
224 PyObject
*item
, *good
;
227 if ((item
= (*sqf
->sq_item
)(seq
, i
)) == NULL
) {
228 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
235 if (func
== Py_None
) {
240 PyObject
*arg
= Py_BuildValue("(O)", item
);
243 good
= PyEval_CallObject(func
, arg
);
250 ok
= PyObject_IsTrue(good
);
254 if (PyList_SetItem(result
, j
++, item
) < 0)
258 int status
= PyList_Append(result
, item
);
270 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
281 static char filter_doc
[] =
282 "filter(function, sequence) -> list\n\
284 Return a list containing those items of sequence for which function(item)\n\
285 is true. If function is None, return a list of items that are true.";
289 builtin_chr(self
, args
)
296 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
298 if (x
< 0 || x
>= 256) {
299 PyErr_SetString(PyExc_ValueError
,
300 "chr() arg not in range(256)");
304 return PyString_FromStringAndSize(s
, 1);
307 static char chr_doc
[] =
308 "chr(i) -> character\n\
310 Return a string of one character with ordinal i; 0 <= i < 256.";
314 builtin_cmp(self
, args
)
321 if (!PyArg_ParseTuple(args
, "OO:cmp", &a
, &b
))
323 if (PyObject_Cmp(a
, b
, &c
) < 0)
325 return PyInt_FromLong((long)c
);
328 static char cmp_doc
[] =
329 "cmp(x, y) -> integer\n\
331 Return negative if x<y, zero if x==y, positive if x>y.";
335 builtin_coerce(self
, args
)
342 if (!PyArg_ParseTuple(args
, "OO:coerce", &v
, &w
))
344 if (PyNumber_Coerce(&v
, &w
) < 0)
346 res
= Py_BuildValue("(OO)", v
, w
);
352 static char coerce_doc
[] =
353 "coerce(x, y) -> None or (x1, y1)\n\
355 When x and y can be coerced to values of the same type, return a tuple\n\
356 containing the coerced values. When they can't be coerced, return None.";
360 builtin_compile(self
, args
)
369 if (!PyArg_ParseTuple(args
, "sss:compile", &str
, &filename
, &startstr
))
371 if (strcmp(startstr
, "exec") == 0)
372 start
= Py_file_input
;
373 else if (strcmp(startstr
, "eval") == 0)
374 start
= Py_eval_input
;
375 else if (strcmp(startstr
, "single") == 0)
376 start
= Py_single_input
;
378 PyErr_SetString(PyExc_ValueError
,
379 "compile() mode must be 'exec' or 'eval' or 'single'");
382 return Py_CompileString(str
, filename
, start
);
385 static char compile_doc
[] =
386 "compile(source, filename, mode) -> code object\n\
388 Compile the source string (a Python module, statement or expression)\n\
389 into a code object that can be executed by the exec statement or eval().\n\
390 The filename will be used for run-time error messages.\n\
391 The mode must be 'exec' to compile a module, 'single' to compile a\n\
392 single (interactive) statement, or 'eval' to compile an expression.";
395 #ifndef WITHOUT_COMPLEX
398 complex_from_string(v
)
401 extern double strtod
Py_PROTO((const char *, char **));
402 char *s
, *start
, *end
;
403 double x
=0.0, y
=0.0, z
;
404 int got_re
=0, got_im
=0, done
=0;
408 char buffer
[256]; /* For errors */
410 start
= s
= PyString_AS_STRING(v
);
412 /* position on first nonblank */
413 while (*s
&& isspace(Py_CHARMASK(*s
)))
416 PyErr_SetString(PyExc_ValueError
,
417 "empty string for complex()");
428 if (s
-start
!= PyString_GET_SIZE(v
)) {
431 "null byte in argument for complex()");
434 if(!done
) sw_error
=1;
441 if (done
) sw_error
=1;
443 if ( *s
=='\0'||*s
=='+'||*s
=='-' ||
444 isspace(Py_CHARMASK(*s
)) ) sw_error
=1;
449 if (got_im
|| done
) {
461 if (*s
!='+' && *s
!='-' )
466 if (isspace(Py_CHARMASK(*s
))) {
467 while (*s
&& isspace(Py_CHARMASK(*s
)))
476 (*s
=='.' || isdigit(Py_CHARMASK(*s
)));
477 if (done
||!digit_or_dot
) {
482 PyFPE_START_PROTECT("strtod", return 0)
483 z
= strtod(s
, &end
) ;
487 "float() out of range: %.150s", s
);
494 if (*s
=='J' || *s
=='j') {
503 /* accept a real part */
511 } /* end of switch */
513 } while (*s
!='\0' && !sw_error
);
516 PyErr_SetString(PyExc_ValueError
,
517 "malformed string for complex()");
521 return PyComplex_FromDoubles(x
,y
);
525 builtin_complex(self
, args
)
529 PyObject
*r
, *i
, *tmp
;
530 PyNumberMethods
*nbr
, *nbi
= NULL
;
535 if (!PyArg_ParseTuple(args
, "O|O:complex", &r
, &i
))
537 if (PyString_Check(r
))
538 return complex_from_string(r
);
539 if ((nbr
= r
->ob_type
->tp_as_number
) == NULL
||
540 nbr
->nb_float
== NULL
||
542 ((nbi
= i
->ob_type
->tp_as_number
) == NULL
||
543 nbi
->nb_float
== NULL
))) {
544 PyErr_SetString(PyExc_TypeError
,
545 "complex() argument can't be converted to complex");
548 /* XXX Hack to support classes with __complex__ method */
549 if (PyInstance_Check(r
)) {
550 static PyObject
*complexstr
;
552 if (complexstr
== NULL
) {
553 complexstr
= PyString_InternFromString("__complex__");
554 if (complexstr
== NULL
)
557 f
= PyObject_GetAttr(r
, complexstr
);
561 PyObject
*args
= Py_BuildValue("()");
564 r
= PyEval_CallObject(f
, args
);
572 if (PyComplex_Check(r
)) {
573 cr
= ((PyComplexObject
*)r
)->cval
;
579 tmp
= (*nbr
->nb_float
)(r
);
585 cr
.real
= PyFloat_AsDouble(tmp
);
593 else if (PyComplex_Check(i
))
594 ci
= ((PyComplexObject
*)i
)->cval
;
596 tmp
= (*nbi
->nb_float
)(i
);
599 ci
.real
= PyFloat_AsDouble(tmp
);
605 return PyComplex_FromCComplex(cr
);
608 static char complex_doc
[] =
609 "complex(real[, imag]) -> complex number\n\
611 Create a complex number from a real part and an optional imaginary part.\n\
612 This is equivalent to (real + imag*1j) where imag defaults to 0.";
618 builtin_dir(self
, args
)
622 static char *attrlist
[] = {"__members__", "__methods__", NULL
};
623 PyObject
*v
= NULL
, *l
= NULL
, *m
= NULL
;
628 if (!PyArg_ParseTuple(args
, "|O:dir", &v
))
631 x
= PyEval_GetLocals();
634 l
= PyMapping_Keys(x
);
639 d
= PyObject_GetAttrString(v
, "__dict__");
643 l
= PyMapping_Keys(d
);
653 for (s
= attrlist
; *s
!= NULL
; s
++) {
654 m
= PyObject_GetAttrString(v
, *s
);
660 x
= PySequence_GetItem(m
, i
);
665 if (PyList_Append(l
, x
) != 0) {
675 if (PyList_Sort(l
) != 0)
683 static char dir_doc
[] =
684 "dir([object]) -> list of strings\n\
686 Return an alphabetized list of names comprising (some of) the attributes\n\
687 of the given object. Without an argument, the names in the current scope\n\
688 are listed. With an instance argument, only the instance attributes are\n\
689 returned. With a class argument, attributes of the base class are not\n\
690 returned. For other types or arguments, this may list members or methods.";
694 builtin_divmod(self
, args
)
700 if (!PyArg_ParseTuple(args
, "OO:divmod", &v
, &w
))
702 return PyNumber_Divmod(v
, w
);
705 static char divmod_doc
[] =
706 "divmod(x, y) -> (div, mod)\n\
708 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
712 builtin_eval(self
, args
)
717 PyObject
*globals
= Py_None
, *locals
= Py_None
;
720 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
722 &PyDict_Type
, &globals
,
723 &PyDict_Type
, &locals
))
725 if (globals
== Py_None
) {
726 globals
= PyEval_GetGlobals();
727 if (locals
== Py_None
)
728 locals
= PyEval_GetLocals();
730 else if (locals
== Py_None
)
732 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
733 if (PyDict_SetItemString(globals
, "__builtins__",
734 PyEval_GetBuiltins()) != 0)
737 if (PyCode_Check(cmd
))
738 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
739 if (!PyString_Check(cmd
)) {
740 PyErr_SetString(PyExc_TypeError
,
741 "eval() argument 1 must be string or code object");
744 str
= PyString_AsString(cmd
);
745 if ((int)strlen(str
) != PyString_Size(cmd
)) {
746 PyErr_SetString(PyExc_ValueError
,
747 "embedded '\\0' in string arg");
750 while (*str
== ' ' || *str
== '\t')
752 return PyRun_String(str
, Py_eval_input
, globals
, locals
);
755 static char eval_doc
[] =
756 "eval(source[, globals[, locals]]) -> value\n\
758 Evaluate the source in the context of globals and locals.\n\
759 The source may be a string representing a Python expression\n\
760 or a code object as returned by compile().\n\
761 The globals and locals are dictionaries, defaulting to the current\n\
762 globals and locals. If only globals is given, locals defaults to it.";
766 builtin_execfile(self
, args
)
771 PyObject
*globals
= Py_None
, *locals
= Py_None
;
775 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
777 &PyDict_Type
, &globals
,
778 &PyDict_Type
, &locals
))
780 if (globals
== Py_None
) {
781 globals
= PyEval_GetGlobals();
782 if (locals
== Py_None
)
783 locals
= PyEval_GetLocals();
785 else if (locals
== Py_None
)
787 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
788 if (PyDict_SetItemString(globals
, "__builtins__",
789 PyEval_GetBuiltins()) != 0)
792 Py_BEGIN_ALLOW_THREADS
793 fp
= fopen(filename
, "r");
796 PyErr_SetFromErrno(PyExc_IOError
);
799 res
= PyRun_File(fp
, filename
, Py_file_input
, globals
, locals
);
800 Py_BEGIN_ALLOW_THREADS
806 static char execfile_doc
[] =
807 "execfile(filename[, globals[, locals]])\n\
809 Read and execute a Python script from a file.\n\
810 The globals and locals are dictionaries, defaulting to the current\n\
811 globals and locals. If only globals is given, locals defaults to it.";
815 builtin_float(self
, args
)
821 if (!PyArg_ParseTuple(args
, "O:float", &v
))
823 return PyNumber_Float(v
);
826 static char float_doc
[] =
827 "float(x) -> floating point number\n\
829 Convert a string or number to a floating point number, if possible.";
833 builtin_getattr(self
, args
)
837 PyObject
*v
, *result
, *dflt
= NULL
;
840 if (!PyArg_ParseTuple(args
, "OS|O:getattr", &v
, &name
, &dflt
))
842 result
= PyObject_GetAttr(v
, name
);
843 if (result
== NULL
&& dflt
!= NULL
) {
851 static char getattr_doc
[] =
852 "getattr(object, name[, default]) -> value\n\
854 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
855 When a default argument is given, it is returned when the attribute doesn't\n\
856 exist; without it, an exception is raised in that case.";
860 builtin_globals(self
, args
)
866 if (!PyArg_ParseTuple(args
, ""))
868 d
= PyEval_GetGlobals();
873 static char globals_doc
[] =
874 "globals() -> dictionary\n\
876 Return the dictionary containing the current scope's global variables.";
880 builtin_hasattr(self
, args
)
887 if (!PyArg_ParseTuple(args
, "OS:hasattr", &v
, &name
))
889 v
= PyObject_GetAttr(v
, name
);
900 static char hasattr_doc
[] =
901 "hasattr(object, name) -> Boolean\n\
903 Return whether the object has an attribute with the given name.\n\
904 (This is done by calling getattr(object, name) and catching exceptions.)";
908 builtin_id(self
, args
)
914 if (!PyArg_ParseTuple(args
, "O:id", &v
))
916 return PyInt_FromLong((long)v
);
919 static char id_doc
[] =
920 "id(object) -> integer\n\
922 Return the identity of an object. This is guaranteed to be unique among\n\
923 simultaneously existing objects. (Hint: it's the object's memory address.)";
927 builtin_map(self
, args
)
933 PySequenceMethods
*sqf
;
937 PyObject
*func
, *result
;
938 sequence
*seqs
= NULL
, *sqp
;
942 n
= PyTuple_Size(args
);
944 PyErr_SetString(PyExc_TypeError
,
945 "map() requires at least two args");
949 func
= PyTuple_GetItem(args
, 0);
952 if (func
== Py_None
&& n
== 1) {
953 /* map(None, S) is the same as list(S). */
954 return PySequence_List(PyTuple_GetItem(args
, 1));
957 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
962 for (len
= 0, i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
964 PySequenceMethods
*sqf
;
966 if ((sqp
->seq
= PyTuple_GetItem(args
, i
+ 1)) == NULL
)
969 sqp
->sqf
= sqf
= sqp
->seq
->ob_type
->tp_as_sequence
;
971 sqf
->sq_length
== NULL
||
972 sqf
->sq_item
== NULL
)
974 static char errmsg
[] =
975 "argument %d to map() must be a sequence object";
976 char errbuf
[sizeof(errmsg
) + 25];
978 sprintf(errbuf
, errmsg
, i
+2);
979 PyErr_SetString(PyExc_TypeError
, errbuf
);
983 if ((curlen
= sqp
->len
= (*sqp
->sqf
->sq_length
)(sqp
->seq
)) < 0)
990 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
994 PyObject
*alist
, *item
=NULL
, *value
;
997 if (func
== Py_None
&& n
== 1)
1000 if ((alist
= PyTuple_New(n
)) == NULL
)
1004 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
1010 item
= (*sqp
->sqf
->sq_item
)(sqp
->seq
, i
);
1012 if (PyErr_ExceptionMatches(
1030 if (PyTuple_SetItem(alist
, j
, item
) < 0) {
1049 if (func
== Py_None
)
1052 value
= PyEval_CallObject(func
, alist
);
1058 int status
= PyList_Append(result
, value
);
1064 if (PyList_SetItem(result
, i
, value
) < 0)
1069 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
1078 if (seqs
) PyMem_DEL(seqs
);
1082 static char map_doc
[] =
1083 "map(function, sequence[, sequence, ...]) -> list\n\
1085 Return a list of the results of applying the function to the items of\n\
1086 the argument sequence(s). If more than one sequence is given, the\n\
1087 function is called with an argument list consisting of the corresponding\n\
1088 item of each sequence, substituting None for missing values when not all\n\
1089 sequences have the same length. If the function is None, return a list of\n\
1090 the items of the sequence (or a list of tuples if more than one sequence).";
1094 builtin_setattr(self
, args
)
1102 if (!PyArg_ParseTuple(args
, "OSO:setattr", &v
, &name
, &value
))
1104 if (PyObject_SetAttr(v
, name
, value
) != 0)
1110 static char setattr_doc
[] =
1111 "setattr(object, name, value)\n\
1113 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1118 builtin_delattr(self
, args
)
1125 if (!PyArg_ParseTuple(args
, "OS:delattr", &v
, &name
))
1127 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1133 static char delattr_doc
[] =
1134 "delattr(object, name)\n\
1136 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1141 builtin_hash(self
, args
)
1148 if (!PyArg_ParseTuple(args
, "O:hash", &v
))
1150 x
= PyObject_Hash(v
);
1153 return PyInt_FromLong(x
);
1156 static char hash_doc
[] =
1157 "hash(object) -> integer\n\
1159 Return a hash value for the object. Two objects with the same value have\n\
1160 the same hash value. The reverse is not necessarily true, but likely.";
1164 builtin_hex(self
, args
)
1169 PyNumberMethods
*nb
;
1171 if (!PyArg_ParseTuple(args
, "O:hex", &v
))
1174 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1175 nb
->nb_hex
== NULL
) {
1176 PyErr_SetString(PyExc_TypeError
,
1177 "hex() argument can't be converted to hex");
1180 return (*nb
->nb_hex
)(v
);
1183 static char hex_doc
[] =
1184 "hex(number) -> string\n\
1186 Return the hexadecimal representation of an integer or long integer.";
1189 static PyObject
*builtin_raw_input
Py_PROTO((PyObject
*, PyObject
*));
1192 builtin_input(self
, args
)
1199 PyObject
*globals
, *locals
;
1201 line
= builtin_raw_input(self
, args
);
1204 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1206 while (*str
== ' ' || *str
== '\t')
1208 globals
= PyEval_GetGlobals();
1209 locals
= PyEval_GetLocals();
1210 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1211 if (PyDict_SetItemString(globals
, "__builtins__",
1212 PyEval_GetBuiltins()) != 0)
1215 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
1220 static char input_doc
[] =
1221 "input([prompt]) -> value\n\
1223 Equivalent to eval(raw_input(prompt)).";
1227 builtin_intern(self
, args
)
1232 if (!PyArg_ParseTuple(args
, "S", &s
))
1235 PyString_InternInPlace(&s
);
1239 static char intern_doc
[] =
1240 "intern(string) -> string\n\
1242 ``Intern'' the given string. This enters the string in the (global)\n\
1243 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1244 Return the string itself or the previously interned string object with the\n\
1249 builtin_int(self
, args
)
1255 if (!PyArg_ParseTuple(args
, "O:int", &v
))
1257 return PyNumber_Int(v
);
1260 static char int_doc
[] =
1261 "int(x) -> integer\n\
1263 Convert a string or number to an integer, if possible.\n\
1264 A floating point argument will be truncated towards zero.";
1268 builtin_len(self
, args
)
1275 if (!PyArg_ParseTuple(args
, "O:len", &v
))
1277 res
= PyObject_Length(v
);
1278 if (res
< 0 && PyErr_Occurred())
1280 return PyInt_FromLong(res
);
1283 static char len_doc
[] =
1284 "len(object) -> integer\n\
1286 Return the number of items of a sequence or mapping.";
1290 builtin_list(self
, args
)
1296 if (!PyArg_ParseTuple(args
, "O:list", &v
))
1298 return PySequence_List(v
);
1301 static char list_doc
[] =
1302 "list(sequence) -> list\n\
1304 Return a new list whose items are the same as those of the argument sequence.";
1308 builtin_slice(self
, args
)
1312 PyObject
*start
, *stop
, *step
;
1314 start
= stop
= step
= NULL
;
1316 if (!PyArg_ParseTuple(args
, "O|OO:slice", &start
, &stop
, &step
))
1319 /* This swapping of stop and start is to maintain similarity with
1325 return PySlice_New(start
, stop
, step
);
1328 static char slice_doc
[] =
1329 "slice([start,] stop[, step]) -> slice object\n\
1331 Create a slice object. This is used for slicing by the Numeric extensions.";
1335 builtin_locals(self
, args
)
1341 if (!PyArg_ParseTuple(args
, ""))
1343 d
= PyEval_GetLocals();
1348 static char locals_doc
[] =
1349 "locals() -> dictionary\n\
1351 Return the dictionary containing the current scope's local variables.";
1355 builtin_long(self
, args
)
1361 if (!PyArg_ParseTuple(args
, "O:long", &v
))
1363 return PyNumber_Long(v
);
1366 static char long_doc
[] =
1367 "long(x) -> long integer\n\
1369 Convert a string or number to a long integer, if possible.\n\
1370 A floating point argument will be truncated towards zero.";
1379 PyObject
*v
, *w
, *x
;
1380 PySequenceMethods
*sq
;
1382 if (PyTuple_Size(args
) > 1)
1384 else if (!PyArg_ParseTuple(args
, "O:min/max", &v
))
1386 sq
= v
->ob_type
->tp_as_sequence
;
1387 if (sq
== NULL
|| sq
->sq_item
== NULL
) {
1388 PyErr_SetString(PyExc_TypeError
,
1389 "min() or max() of non-sequence");
1393 for (i
= 0; ; i
++) {
1394 x
= (*sq
->sq_item
)(v
, i
); /* Implies INCREF */
1396 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1406 int c
= PyObject_Compare(x
, w
);
1407 if (c
&& PyErr_Occurred()) {
1421 PyErr_SetString(PyExc_ValueError
,
1422 "min() or max() of empty sequence");
1427 builtin_min(self
, v
)
1431 return min_max(v
, -1);
1434 static char min_doc
[] =
1435 "min(sequence) -> value\n\
1436 min(a, b, c, ...) -> value\n\
1438 With a single sequence argument, return its smallest item.\n\
1439 With two or more arguments, return the smallest argument.";
1443 builtin_max(self
, v
)
1447 return min_max(v
, 1);
1450 static char max_doc
[] =
1451 "max(sequence) -> value\n\
1452 max(a, b, c, ...) -> value\n\
1454 With a single sequence argument, return its largest item.\n\
1455 With two or more arguments, return the largest argument.";
1459 builtin_oct(self
, 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(self
, args
)
1493 if (!PyArg_ParseTuple(args
, "s|si:open", &name
, &mode
, &bufsize
))
1495 f
= PyFile_FromString(name
, mode
);
1497 PyFile_SetBufSize(f
, bufsize
);
1501 static char open_doc
[] =
1502 "open(filename[, mode[, buffering]]) -> file object\n\
1504 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1505 writing or appending. The file will be created if it doesn't exist\n\
1506 when opened for writing or appending; it will be truncated when\n\
1507 opened for writing. Add a 'b' to the mode for binary files.\n\
1508 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1509 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1510 buffered, and larger numbers specify the buffer size.";
1514 builtin_ord(self
, args
)
1520 if (!PyArg_ParseTuple(args
, "c:ord", &c
))
1522 return PyInt_FromLong((long)(c
& 0xff));
1525 static char ord_doc
[] =
1526 "ord(c) -> integer\n\
1528 Return the integer ordinal of a one character string.";
1532 builtin_pow(self
, args
)
1536 PyObject
*v
, *w
, *z
= Py_None
;
1538 if (!PyArg_ParseTuple(args
, "OO|O:pow", &v
, &w
, &z
))
1540 return PyNumber_Power(v
, w
, z
);
1543 static char pow_doc
[] =
1544 "pow(x, y[, z]) -> number\n\
1546 With two arguments, equivalent to x**y. With three arguments,\n\
1547 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1550 /* Return number of items in range/xrange (lo, hi, step). step > 0
1551 * required. Return a value < 0 if & only if the true value is too
1552 * large to fit in a signed long.
1555 get_len_of_range(lo
, hi
, step
)
1558 long step
; /* must be > 0 */
1560 /* -------------------------------------------------------------
1561 If lo >= hi, the range is empty.
1562 Else if n values are in the range, the last one is
1563 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1564 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1565 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1566 the RHS is non-negative and so truncation is the same as the
1567 floor. Letting M be the largest positive long, the worst case
1568 for the RHS numerator is hi=M, lo=-M-1, and then
1569 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1570 precision to compute the RHS exactly.
1571 ---------------------------------------------------------------*/
1574 unsigned long uhi
= (unsigned long)hi
;
1575 unsigned long ulo
= (unsigned long)lo
;
1576 unsigned long diff
= uhi
- ulo
- 1;
1577 n
= (long)(diff
/ (unsigned long)step
+ 1);
1583 builtin_range(self
, args
)
1587 long ilow
= 0, ihigh
= 0, istep
= 1;
1593 if (PyTuple_Size(args
) <= 1) {
1594 if (!PyArg_ParseTuple(args
,
1595 "l;range() requires 1-3 int arguments",
1600 if (!PyArg_ParseTuple(args
,
1601 "ll|l;range() requires 1-3 int arguments",
1602 &ilow
, &ihigh
, &istep
))
1606 PyErr_SetString(PyExc_ValueError
, "zero step for range()");
1610 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1612 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1614 if (bign
< 0 || (long)n
!= bign
) {
1615 PyErr_SetString(PyExc_OverflowError
,
1616 "range() has too many items");
1622 for (i
= 0; i
< n
; i
++) {
1623 PyObject
*w
= PyInt_FromLong(ilow
);
1628 PyList_SET_ITEM(v
, i
, w
);
1634 static char range_doc
[] =
1635 "range([start,] stop[, step]) -> list of integers\n\
1637 Return a list containing an arithmetic progression of integers.\n\
1638 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1639 When step is given, it specifies the increment (or decrement).\n\
1640 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1641 These are exactly the valid indices for a list of 4 elements.";
1645 builtin_xrange(self
, args
)
1649 long ilow
= 0, ihigh
= 0, istep
= 1;
1652 if (PyTuple_Size(args
) <= 1) {
1653 if (!PyArg_ParseTuple(args
,
1654 "l;xrange() requires 1-3 int arguments",
1659 if (!PyArg_ParseTuple(args
,
1660 "ll|l;xrange() requires 1-3 int arguments",
1661 &ilow
, &ihigh
, &istep
))
1665 PyErr_SetString(PyExc_ValueError
, "zero step for xrange()");
1669 n
= get_len_of_range(ilow
, ihigh
, istep
);
1671 n
= get_len_of_range(ihigh
, ilow
, -istep
);
1673 PyErr_SetString(PyExc_OverflowError
,
1674 "xrange() has more than sys.maxint items");
1677 return PyRange_New(ilow
, n
, istep
, 1);
1680 static char xrange_doc
[] =
1681 "xrange([start,] stop[, step]) -> xrange object\n\
1683 Like range(), but instead of returning a list, returns an object that\n\
1684 generates the numbers in the range on demand. This is slightly slower\n\
1685 than range() but more memory efficient.";
1689 builtin_raw_input(self
, args
)
1696 if (!PyArg_ParseTuple(args
, "|O:[raw_]input", &v
))
1698 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin
&&
1699 PyFile_AsFile(PySys_GetObject("stdout")) == stdout
&&
1700 isatty(fileno(stdin
)) && isatty(fileno(stdout
))) {
1706 po
= PyObject_Str(v
);
1709 prompt
= PyString_AsString(po
);
1717 s
= PyOS_Readline(prompt
);
1720 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1724 PyErr_SetNone(PyExc_EOFError
);
1727 else { /* strip trailing '\n' */
1728 result
= PyString_FromStringAndSize(s
, strlen(s
)-1);
1734 f
= PySys_GetObject("stdout");
1736 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
1739 if (Py_FlushLine() != 0 ||
1740 PyFile_WriteObject(v
, f
, Py_PRINT_RAW
) != 0)
1743 f
= PySys_GetObject("stdin");
1745 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdin");
1748 return PyFile_GetLine(f
, -1);
1751 static char raw_input_doc
[] =
1752 "raw_input([prompt]) -> string\n\
1754 Read a string from standard input. The trailing newline is stripped.\n\
1755 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1756 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1757 is printed without a trailing newline before reading.";
1761 builtin_reduce(self
, args
)
1765 PyObject
*seq
, *func
, *result
= NULL
;
1766 PySequenceMethods
*sqf
;
1769 if (!PyArg_ParseTuple(args
, "OO|O:reduce", &func
, &seq
, &result
))
1774 sqf
= seq
->ob_type
->tp_as_sequence
;
1775 if (sqf
== NULL
|| sqf
->sq_item
== NULL
) {
1776 PyErr_SetString(PyExc_TypeError
,
1777 "2nd argument to reduce() must be a sequence object");
1781 if ((args
= PyTuple_New(2)) == NULL
)
1784 for (i
= 0; ; ++i
) {
1787 if (args
->ob_refcnt
> 1) {
1789 if ((args
= PyTuple_New(2)) == NULL
)
1793 if ((op2
= (*sqf
->sq_item
)(seq
, i
)) == NULL
) {
1794 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1804 PyTuple_SetItem(args
, 0, result
);
1805 PyTuple_SetItem(args
, 1, op2
);
1806 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1814 PyErr_SetString(PyExc_TypeError
,
1815 "reduce of empty sequence with no initial value");
1825 static char reduce_doc
[] =
1826 "reduce(function, sequence[, initial]) -> value\n\
1828 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1829 from left to right, so as to reduce the sequence to a single value.\n\
1830 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1831 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1832 of the sequence in the calculation, and serves as a default when the\n\
1833 sequence is empty.";
1837 builtin_reload(self
, args
)
1843 if (!PyArg_ParseTuple(args
, "O:reload", &v
))
1845 return PyImport_ReloadModule(v
);
1848 static char reload_doc
[] =
1849 "reload(module) -> module\n\
1851 Reload the module. The module must have been successfully imported before.";
1855 builtin_repr(self
, args
)
1861 if (!PyArg_ParseTuple(args
, "O:repr", &v
))
1863 return PyObject_Repr(v
);
1866 static char repr_doc
[] =
1867 "repr(object) -> string\n\
1869 Return the canonical string representation of the object.\n\
1870 For most object types, eval(repr(object)) == object.";
1874 builtin_round(self
, args
)
1883 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1901 return PyFloat_FromDouble(x
);
1904 static char round_doc
[] =
1905 "round(number[, ndigits]) -> floating point number\n\
1907 Round a number to a given precision in decimal digits (default 0 digits).\n\
1908 This always returns a floating point number. Precision may be negative.";
1912 builtin_str(self
, args
)
1918 if (!PyArg_ParseTuple(args
, "O:str", &v
))
1920 return PyObject_Str(v
);
1923 static char str_doc
[] =
1924 "str(object) -> string\n\
1926 Return a nice string representation of the object.\n\
1927 If the argument is a string, the return value is the same object.";
1931 builtin_tuple(self
, args
)
1937 if (!PyArg_ParseTuple(args
, "O:tuple", &v
))
1939 return PySequence_Tuple(v
);
1942 static char tuple_doc
[] =
1943 "tuple(sequence) -> list\n\
1945 Return a tuple whose items are the same as those of the argument sequence.\n\
1946 If the argument is a tuple, the return value is the same object.";
1950 builtin_type(self
, args
)
1956 if (!PyArg_ParseTuple(args
, "O:type", &v
))
1958 v
= (PyObject
*)v
->ob_type
;
1963 static char type_doc
[] =
1964 "type(object) -> type object\n\
1966 Return the type of the object.";
1970 builtin_vars(self
, args
)
1977 if (!PyArg_ParseTuple(args
, "|O:vars", &v
))
1980 d
= PyEval_GetLocals();
1982 if (!PyErr_Occurred())
1983 PyErr_SetString(PyExc_SystemError
,
1990 d
= PyObject_GetAttrString(v
, "__dict__");
1992 PyErr_SetString(PyExc_TypeError
,
1993 "vars() argument must have __dict__ attribute");
2000 static char vars_doc
[] =
2001 "vars([object]) -> dictionary\n\
2003 Without arguments, equivalent to locals().\n\
2004 With an argument, equivalent to object.__dict__.";
2007 abstract_issubclass(derived
, cls
, err
, first
)
2013 static PyObject
*__bases__
= NULL
;
2018 if (__bases__
== NULL
) {
2019 __bases__
= PyString_FromString("__bases__");
2020 if (__bases__
== NULL
)
2025 bases
= PyObject_GetAttr(cls
, __bases__
);
2026 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
2028 PyErr_SetString(PyExc_TypeError
, err
);
2037 bases
= PyObject_GetAttr(derived
, __bases__
);
2038 if (bases
== NULL
|| !PyTuple_Check(bases
)) {
2040 PyErr_SetString(PyExc_TypeError
, err
);
2044 n
= PyTuple_GET_SIZE(bases
);
2045 for (i
= 0; i
< n
; i
++) {
2046 r
= abstract_issubclass(PyTuple_GET_ITEM(bases
, i
),
2058 builtin_isinstance(self
, args
)
2065 static PyObject
*__class__
= NULL
;
2068 if (!PyArg_ParseTuple(args
, "OO", &inst
, &cls
))
2071 if (PyClass_Check(cls
)) {
2072 if (PyInstance_Check(inst
)) {
2074 (PyObject
*)((PyInstanceObject
*)inst
)->in_class
;
2075 retval
= PyClass_IsSubclass(inclass
, cls
);
2078 else if (PyType_Check(cls
)) {
2079 retval
= ((PyObject
*)(inst
->ob_type
) == cls
);
2081 else if (!PyInstance_Check(inst
)) {
2082 if (__class__
== NULL
) {
2083 __class__
= PyString_FromString("__class__");
2084 if (__class__
== NULL
)
2087 icls
= PyObject_GetAttr(inst
, __class__
);
2089 retval
= abstract_issubclass(
2091 "second argument must be a class",
2098 PyErr_SetString(PyExc_TypeError
,
2099 "second argument must be a class");
2104 PyErr_SetString(PyExc_TypeError
,
2105 "second argument must be a class");
2108 return PyInt_FromLong(retval
);
2111 static char isinstance_doc
[] =
2112 "isinstance(object, class-or-type) -> Boolean\n\
2114 Return whether an object is an instance of a class or of a subclass thereof.\n\
2115 With a type as second argument, return whether that is the object's type.";
2119 builtin_issubclass(self
, args
)
2127 if (!PyArg_ParseTuple(args
, "OO", &derived
, &cls
))
2130 if (!PyClass_Check(derived
) || !PyClass_Check(cls
)) {
2131 retval
= abstract_issubclass(
2132 derived
, cls
, "arguments must be classes", 1);
2138 if (!(retval
= (derived
== cls
)))
2139 retval
= PyClass_IsSubclass(derived
, cls
);
2142 return PyInt_FromLong(retval
);
2145 static char issubclass_doc
[] =
2146 "issubclass(C, B) -> Boolean\n\
2148 Return whether class C is a subclass (i.e., a derived class) of class B.";
2151 static PyMethodDef builtin_methods
[] = {
2152 {"__import__", builtin___import__
, 1, import_doc
},
2153 {"abs", builtin_abs
, 1, abs_doc
},
2154 {"apply", builtin_apply
, 1, apply_doc
},
2155 {"buffer", builtin_buffer
, 1, buffer_doc
},
2156 {"callable", builtin_callable
, 1, callable_doc
},
2157 {"chr", builtin_chr
, 1, chr_doc
},
2158 {"cmp", builtin_cmp
, 1, cmp_doc
},
2159 {"coerce", builtin_coerce
, 1, coerce_doc
},
2160 {"compile", builtin_compile
, 1, compile_doc
},
2161 #ifndef WITHOUT_COMPLEX
2162 {"complex", builtin_complex
, 1, complex_doc
},
2164 {"delattr", builtin_delattr
, 1, delattr_doc
},
2165 {"dir", builtin_dir
, 1, dir_doc
},
2166 {"divmod", builtin_divmod
, 1, divmod_doc
},
2167 {"eval", builtin_eval
, 1, eval_doc
},
2168 {"execfile", builtin_execfile
, 1, execfile_doc
},
2169 {"filter", builtin_filter
, 1, filter_doc
},
2170 {"float", builtin_float
, 1, float_doc
},
2171 {"getattr", builtin_getattr
, 1, getattr_doc
},
2172 {"globals", builtin_globals
, 1, globals_doc
},
2173 {"hasattr", builtin_hasattr
, 1, hasattr_doc
},
2174 {"hash", builtin_hash
, 1, hash_doc
},
2175 {"hex", builtin_hex
, 1, hex_doc
},
2176 {"id", builtin_id
, 1, id_doc
},
2177 {"input", builtin_input
, 1, input_doc
},
2178 {"intern", builtin_intern
, 1, intern_doc
},
2179 {"int", builtin_int
, 1, int_doc
},
2180 {"isinstance", builtin_isinstance
, 1, isinstance_doc
},
2181 {"issubclass", builtin_issubclass
, 1, issubclass_doc
},
2182 {"len", builtin_len
, 1, len_doc
},
2183 {"list", builtin_list
, 1, list_doc
},
2184 {"locals", builtin_locals
, 1, locals_doc
},
2185 {"long", builtin_long
, 1, long_doc
},
2186 {"map", builtin_map
, 1, map_doc
},
2187 {"max", builtin_max
, 1, max_doc
},
2188 {"min", builtin_min
, 1, min_doc
},
2189 {"oct", builtin_oct
, 1, oct_doc
},
2190 {"open", builtin_open
, 1, open_doc
},
2191 {"ord", builtin_ord
, 1, ord_doc
},
2192 {"pow", builtin_pow
, 1, pow_doc
},
2193 {"range", builtin_range
, 1, range_doc
},
2194 {"raw_input", builtin_raw_input
, 1, raw_input_doc
},
2195 {"reduce", builtin_reduce
, 1, reduce_doc
},
2196 {"reload", builtin_reload
, 1, reload_doc
},
2197 {"repr", builtin_repr
, 1, repr_doc
},
2198 {"round", builtin_round
, 1, round_doc
},
2199 {"setattr", builtin_setattr
, 1, setattr_doc
},
2200 {"slice", builtin_slice
, 1, slice_doc
},
2201 {"str", builtin_str
, 1, str_doc
},
2202 {"tuple", builtin_tuple
, 1, tuple_doc
},
2203 {"type", builtin_type
, 1, type_doc
},
2204 {"vars", builtin_vars
, 1, vars_doc
},
2205 {"xrange", builtin_xrange
, 1, xrange_doc
},
2209 /* Predefined exceptions */
2211 PyObject
*PyExc_Exception
;
2212 PyObject
*PyExc_StandardError
;
2213 PyObject
*PyExc_ArithmeticError
;
2214 PyObject
*PyExc_LookupError
;
2216 PyObject
*PyExc_AssertionError
;
2217 PyObject
*PyExc_AttributeError
;
2218 PyObject
*PyExc_EOFError
;
2219 PyObject
*PyExc_FloatingPointError
;
2220 PyObject
*PyExc_EnvironmentError
;
2221 PyObject
*PyExc_IOError
;
2222 PyObject
*PyExc_OSError
;
2223 PyObject
*PyExc_ImportError
;
2224 PyObject
*PyExc_IndexError
;
2225 PyObject
*PyExc_KeyError
;
2226 PyObject
*PyExc_KeyboardInterrupt
;
2227 PyObject
*PyExc_MemoryError
;
2228 PyObject
*PyExc_NameError
;
2229 PyObject
*PyExc_OverflowError
;
2230 PyObject
*PyExc_RuntimeError
;
2231 PyObject
*PyExc_NotImplementedError
;
2232 PyObject
*PyExc_SyntaxError
;
2233 PyObject
*PyExc_SystemError
;
2234 PyObject
*PyExc_SystemExit
;
2235 PyObject
*PyExc_UnboundLocalError
;
2236 PyObject
*PyExc_TypeError
;
2237 PyObject
*PyExc_ValueError
;
2238 PyObject
*PyExc_ZeroDivisionError
;
2240 PyObject
*PyExc_MemoryErrorInst
;
2249 {"Exception", &PyExc_Exception
, 0},
2250 {"StandardError", &PyExc_StandardError
, 0},
2251 {"ArithmeticError", &PyExc_ArithmeticError
, 0},
2252 {"LookupError", &PyExc_LookupError
, 0},
2253 {"AssertionError", &PyExc_AssertionError
, 1},
2254 {"AttributeError", &PyExc_AttributeError
, 1},
2255 {"EOFError", &PyExc_EOFError
, 1},
2256 {"FloatingPointError", &PyExc_FloatingPointError
, 1},
2257 {"EnvironmentError", &PyExc_EnvironmentError
, 0},
2258 {"IOError", &PyExc_IOError
, 1},
2259 {"OSError", &PyExc_OSError
, 1},
2260 {"ImportError", &PyExc_ImportError
, 1},
2261 {"IndexError", &PyExc_IndexError
, 1},
2262 {"KeyError", &PyExc_KeyError
, 1},
2263 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt
, 1},
2264 {"MemoryError", &PyExc_MemoryError
, 1},
2265 /* Note: NameError is not a leaf in exceptions.py, but unlike
2266 the other non-leafs NameError is meant to be raised directly
2267 at times -- the leaf_exc member really seems to mean something
2268 like "this is an abstract base class" when false.
2270 {"NameError", &PyExc_NameError
, 1},
2271 {"OverflowError", &PyExc_OverflowError
, 1},
2272 {"RuntimeError", &PyExc_RuntimeError
, 1},
2273 {"NotImplementedError",&PyExc_NotImplementedError
,1},
2274 {"SyntaxError", &PyExc_SyntaxError
, 1},
2275 {"SystemError", &PyExc_SystemError
, 1},
2276 {"SystemExit", &PyExc_SystemExit
, 1},
2277 {"UnboundLocalError", &PyExc_UnboundLocalError
, 1},
2278 {"TypeError", &PyExc_TypeError
, 1},
2279 {"ValueError", &PyExc_ValueError
, 1},
2280 {"ZeroDivisionError", &PyExc_ZeroDivisionError
, 1},
2285 /* import exceptions module to extract class exceptions. on success,
2286 * return 1. on failure return 0 which signals _PyBuiltin_Init_2 to fall
2287 * back to using old-style string based exceptions.
2290 init_class_exc(dict
)
2294 PyObject
*m
= PyImport_ImportModule("exceptions");
2295 PyObject
*args
= NULL
;
2298 /* make sure we got the module and its dictionary */
2300 (d
= PyModule_GetDict(m
)) == NULL
)
2302 PySys_WriteStderr("'import exceptions' failed; ");
2303 if (Py_VerboseFlag
) {
2304 PySys_WriteStderr("traceback:\n");
2308 PySys_WriteStderr("use -v for traceback\n");
2312 for (i
= 0; bltin_exc
[i
].name
; i
++) {
2313 /* dig the exception out of the module */
2314 PyObject
*exc
= PyDict_GetItemString(d
, bltin_exc
[i
].name
);
2317 "Built-in exception class not found: %s. Library mismatch?\n",
2321 /* free the old-style exception string object */
2322 Py_XDECREF(*bltin_exc
[i
].exc
);
2324 /* squirrel away a pointer to the exception */
2326 *bltin_exc
[i
].exc
= exc
;
2328 /* and insert the name in the __builtin__ module */
2329 if (PyDict_SetItemString(dict
, bltin_exc
[i
].name
, exc
)) {
2331 "Cannot insert exception into __builtin__: %s\n",
2337 /* we need one pre-allocated instance */
2338 args
= Py_BuildValue("()");
2340 !(PyExc_MemoryErrorInst
=
2341 PyEval_CallObject(PyExc_MemoryError
, args
)))
2343 PySys_WriteStderr("Cannot pre-allocate MemoryError instance\n");
2348 /* we're done with the exceptions module */
2351 if (PyErr_Occurred()) {
2352 PySys_WriteStderr("Cannot initialize standard class exceptions; ");
2353 if (Py_VerboseFlag
) {
2354 PySys_WriteStderr("traceback:\n");
2358 PySys_WriteStderr("use -v for traceback\n");
2373 Py_XDECREF(PyExc_MemoryErrorInst
);
2374 PyExc_MemoryErrorInst
= NULL
;
2379 newstdexception(dict
, name
)
2383 PyObject
*v
= PyString_FromString(name
);
2384 if (v
== NULL
|| PyDict_SetItemString(dict
, name
, v
) != 0)
2385 Py_FatalError("Cannot create string-based exceptions");
2395 for (i
= 0; bltin_exc
[i
].name
; i
++, exccnt
++) {
2396 Py_XDECREF(*bltin_exc
[i
].exc
);
2397 if (bltin_exc
[i
].leaf_exc
)
2399 newstdexception(dict
, bltin_exc
[i
].name
);
2402 /* This is kind of bogus because we special case the some of the
2403 * new exceptions to be nearly forward compatible. But this means
2404 * we hard code knowledge about exceptions.py into C here. I don't
2405 * have a better solution, though.
2407 PyExc_LookupError
= PyTuple_New(2);
2408 Py_INCREF(PyExc_IndexError
);
2409 PyTuple_SET_ITEM(PyExc_LookupError
, 0, PyExc_IndexError
);
2410 Py_INCREF(PyExc_KeyError
);
2411 PyTuple_SET_ITEM(PyExc_LookupError
, 1, PyExc_KeyError
);
2412 PyDict_SetItemString(dict
, "LookupError", PyExc_LookupError
);
2414 PyExc_ArithmeticError
= PyTuple_New(3);
2415 Py_INCREF(PyExc_OverflowError
);
2416 PyTuple_SET_ITEM(PyExc_ArithmeticError
, 0, PyExc_OverflowError
);
2417 Py_INCREF(PyExc_ZeroDivisionError
);
2418 PyTuple_SET_ITEM(PyExc_ArithmeticError
, 1, PyExc_ZeroDivisionError
);
2419 Py_INCREF(PyExc_FloatingPointError
);
2420 PyTuple_SET_ITEM(PyExc_ArithmeticError
, 2, PyExc_FloatingPointError
);
2421 PyDict_SetItemString(dict
, "ArithmeticError", PyExc_ArithmeticError
);
2423 PyExc_EnvironmentError
= PyTuple_New(2);
2424 Py_INCREF(PyExc_IOError
);
2425 PyTuple_SET_ITEM(PyExc_EnvironmentError
, 0, PyExc_IOError
);
2426 Py_INCREF(PyExc_OSError
);
2427 PyTuple_SET_ITEM(PyExc_EnvironmentError
, 1, PyExc_OSError
);
2428 PyDict_SetItemString(dict
, "EnvironmentError", PyExc_EnvironmentError
);
2430 /* Make UnboundLocalError an alias for NameError */
2431 Py_INCREF(PyExc_NameError
);
2432 Py_DECREF(PyExc_UnboundLocalError
);
2433 PyExc_UnboundLocalError
= PyExc_NameError
;
2434 if (PyDict_SetItemString(dict
, "UnboundLocalError",
2435 PyExc_NameError
) != 0)
2436 Py_FatalError("Cannot create string-based exceptions");
2438 /* missing from the StandardError tuple: Exception, StandardError,
2441 PyExc_StandardError
= PyTuple_New(exccnt
-3);
2442 for (i
= 2, j
= 0; bltin_exc
[i
].name
; i
++) {
2443 PyObject
*exc
= *bltin_exc
[i
].exc
;
2444 /* SystemExit is not an error, but it is an exception */
2445 if (exc
!= PyExc_SystemExit
) {
2447 PyTuple_SET_ITEM(PyExc_StandardError
, j
++, exc
);
2450 PyDict_SetItemString(dict
, "StandardError", PyExc_StandardError
);
2452 /* Exception is a 2-tuple */
2453 PyExc_Exception
= PyTuple_New(2);
2454 Py_INCREF(PyExc_SystemExit
);
2455 PyTuple_SET_ITEM(PyExc_Exception
, 0, PyExc_SystemExit
);
2456 Py_INCREF(PyExc_StandardError
);
2457 PyTuple_SET_ITEM(PyExc_Exception
, 1, PyExc_StandardError
);
2458 PyDict_SetItemString(dict
, "Exception", PyExc_Exception
);
2460 if (PyErr_Occurred())
2461 Py_FatalError("Could not initialize built-in string exceptions");
2469 for (i
= 0; bltin_exc
[i
].name
; i
++) {
2470 PyObject
*exc
= *bltin_exc
[i
].exc
;
2472 *bltin_exc
[i
].exc
= NULL
;
2476 static char builtin_doc
[] =
2477 "Built-in functions, exceptions, and other objects.\n\
2479 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2484 PyObject
*mod
, *dict
;
2485 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2486 builtin_doc
, (PyObject
*)NULL
,
2487 PYTHON_API_VERSION
);
2490 dict
= PyModule_GetDict(mod
);
2492 if (PyDict_SetItemString(dict
, "None", Py_None
) < 0)
2494 if (PyDict_SetItemString(dict
, "Ellipsis", Py_Ellipsis
) < 0)
2496 if (PyDict_SetItemString(dict
, "__debug__",
2497 PyInt_FromLong(Py_OptimizeFlag
== 0)) < 0)
2504 _PyBuiltin_Init_2(dict
)
2507 /* if Python was started with -X, initialize the class exceptions */
2508 if (Py_UseClassExceptionsFlag
) {
2509 if (!init_class_exc(dict
)) {
2510 /* class based exceptions could not be
2511 * initialized. Fall back to using string based
2515 "Warning! Falling back to string-based exceptions\n");
2536 /* Helper for filter(): filter a tuple through a function */
2539 filtertuple(func
, tuple
)
2545 int len
= PyTuple_Size(tuple
);
2552 if ((result
= PyTuple_New(len
)) == NULL
)
2555 for (i
= j
= 0; i
< len
; ++i
) {
2556 PyObject
*item
, *good
;
2559 if ((item
= PyTuple_GetItem(tuple
, i
)) == NULL
)
2561 if (func
== Py_None
) {
2566 PyObject
*arg
= Py_BuildValue("(O)", item
);
2569 good
= PyEval_CallObject(func
, arg
);
2574 ok
= PyObject_IsTrue(good
);
2578 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2583 if (_PyTuple_Resize(&result
, j
, 0) < 0)
2594 /* Helper for filter(): filter a string through a function */
2597 filterstring(func
, strobj
)
2603 int len
= PyString_Size(strobj
);
2605 if (func
== Py_None
) {
2606 /* No character is ever false -- share input string */
2610 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2613 for (i
= j
= 0; i
< len
; ++i
) {
2614 PyObject
*item
, *arg
, *good
;
2617 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2620 arg
= Py_BuildValue("(O)", item
);
2624 good
= PyEval_CallObject(func
, arg
);
2628 ok
= PyObject_IsTrue(good
);
2631 PyString_AS_STRING((PyStringObject
*)result
)[j
++] =
2632 PyString_AS_STRING((PyStringObject
*)item
)[0];
2635 if (j
< len
&& _PyString_Resize(&result
, j
) < 0)