2 /* Built-in functions */
13 #include "unixstuff.h"
16 /* The default encoding used by the platform file system APIs
17 Can remain NULL for all platforms that don't have such a concept
19 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
20 const char *Py_FileSystemDefaultEncoding
= "mbcs";
21 #elif defined(__APPLE__)
22 const char *Py_FileSystemDefaultEncoding
= "utf-8";
24 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
28 static PyObject
*filterstring(PyObject
*, PyObject
*);
29 #ifdef Py_USING_UNICODE
30 static PyObject
*filterunicode(PyObject
*, PyObject
*);
32 static PyObject
*filtertuple (PyObject
*, PyObject
*);
35 builtin___import__(PyObject
*self
, PyObject
*args
)
38 PyObject
*globals
= NULL
;
39 PyObject
*locals
= NULL
;
40 PyObject
*fromlist
= NULL
;
42 if (!PyArg_ParseTuple(args
, "s|OOO:__import__",
43 &name
, &globals
, &locals
, &fromlist
))
45 return PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
);
48 PyDoc_STRVAR(import_doc
,
49 "__import__(name, globals, locals, fromlist) -> module\n\
51 Import a module. The globals are only used to determine the context;\n\
52 they are not modified. The locals are currently unused. The fromlist\n\
53 should be a list of names to emulate ``from name import ...'', or an\n\
54 empty list to emulate ``import name''.\n\
55 When importing a module from a package, note that __import__('A.B', ...)\n\
56 returns package A when fromlist is empty, but its submodule B when\n\
57 fromlist is not empty.");
61 builtin_abs(PyObject
*self
, PyObject
*v
)
63 return PyNumber_Absolute(v
);
67 "abs(number) -> number\n\
69 Return the absolute value of the argument.");
73 builtin_apply(PyObject
*self
, PyObject
*args
)
75 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
76 PyObject
*t
= NULL
, *retval
= NULL
;
78 if (PyErr_Warn(PyExc_PendingDeprecationWarning
,
79 "use func(*args, **kwargs) instead of "
80 "apply(func, args, kwargs)") < 0)
82 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
85 if (!PyTuple_Check(alist
)) {
86 if (!PySequence_Check(alist
)) {
87 PyErr_Format(PyExc_TypeError
,
88 "apply() arg 2 expected sequence, found %s",
89 alist
->ob_type
->tp_name
);
92 t
= PySequence_Tuple(alist
);
98 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
99 PyErr_Format(PyExc_TypeError
,
100 "apply() arg 3 expected dictionary, found %s",
101 kwdict
->ob_type
->tp_name
);
104 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
110 PyDoc_STRVAR(apply_doc
,
111 "apply(object[, args[, kwargs]]) -> value\n\
113 Call a callable object with positional arguments taken from the tuple args,\n\
114 and keyword arguments taken from the optional dictionary kwargs.\n\
115 Note that classes are callable, as are instances with a __call__() method.\n\
117 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
118 function(*args, **keywords).");
122 builtin_callable(PyObject
*self
, PyObject
*v
)
124 return PyBool_FromLong((long)PyCallable_Check(v
));
127 PyDoc_STRVAR(callable_doc
,
128 "callable(object) -> bool\n\
130 Return whether the object is callable (i.e., some kind of function).\n\
131 Note that classes are callable, as are instances with a __call__() method.");
135 builtin_filter(PyObject
*self
, PyObject
*args
)
137 PyObject
*func
, *seq
, *result
, *it
, *arg
;
138 int len
; /* guess for result list size */
141 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
144 /* Strings and tuples return a result of the same type. */
145 if (PyString_Check(seq
))
146 return filterstring(func
, seq
);
147 #ifdef Py_USING_UNICODE
148 if (PyUnicode_Check(seq
))
149 return filterunicode(func
, seq
);
151 if (PyTuple_Check(seq
))
152 return filtertuple(func
, seq
);
155 it
= PyObject_GetIter(seq
);
159 /* Guess a result list size. */
160 len
= -1; /* unknown */
161 if (PySequence_Check(seq
) &&
162 seq
->ob_type
->tp_as_sequence
->sq_length
) {
163 len
= PySequence_Size(seq
);
168 len
= 8; /* arbitrary */
170 /* Pre-allocate argument list tuple. */
171 arg
= PyTuple_New(1);
175 /* Get a result list. */
176 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
177 /* Eww - can modify the list in-place. */
182 result
= PyList_New(len
);
187 /* Build the result list. */
193 item
= PyIter_Next(it
);
195 if (PyErr_Occurred())
200 if (func
== Py_None
) {
201 ok
= PyObject_IsTrue(item
);
205 PyTuple_SET_ITEM(arg
, 0, item
);
206 good
= PyObject_Call(func
, arg
, NULL
);
207 PyTuple_SET_ITEM(arg
, 0, NULL
);
212 ok
= PyObject_IsTrue(good
);
217 PyList_SET_ITEM(result
, j
, item
);
219 int status
= PyList_Append(result
, item
);
231 /* Cut back result list if len is too big. */
232 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
248 PyDoc_STRVAR(filter_doc
,
249 "filter(function or None, sequence) -> list, tuple, or string\n"
251 "Return those items of sequence for which function(item) is true. If\n"
252 "function is None, return the items that are true. If sequence is a tuple\n"
253 "or string, return the same type, else return a list.");
256 builtin_chr(PyObject
*self
, PyObject
*args
)
261 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
263 if (x
< 0 || x
>= 256) {
264 PyErr_SetString(PyExc_ValueError
,
265 "chr() arg not in range(256)");
269 return PyString_FromStringAndSize(s
, 1);
272 PyDoc_STRVAR(chr_doc
,
273 "chr(i) -> character\n\
275 Return a string of one character with ordinal i; 0 <= i < 256.");
278 #ifdef Py_USING_UNICODE
280 builtin_unichr(PyObject
*self
, PyObject
*args
)
284 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
287 return PyUnicode_FromOrdinal(x
);
290 PyDoc_STRVAR(unichr_doc
,
291 "unichr(i) -> Unicode character\n\
293 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
298 builtin_cmp(PyObject
*self
, PyObject
*args
)
303 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
305 if (PyObject_Cmp(a
, b
, &c
) < 0)
307 return PyInt_FromLong((long)c
);
310 PyDoc_STRVAR(cmp_doc
,
311 "cmp(x, y) -> integer\n\
313 Return negative if x<y, zero if x==y, positive if x>y.");
317 builtin_coerce(PyObject
*self
, PyObject
*args
)
322 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
324 if (PyNumber_Coerce(&v
, &w
) < 0)
326 res
= Py_BuildValue("(OO)", v
, w
);
332 PyDoc_STRVAR(coerce_doc
,
333 "coerce(x, y) -> None or (x1, y1)\n\
335 When x and y can be coerced to values of the same type, return a tuple\n\
336 containing the coerced values. When they can't be coerced, return None.");
340 builtin_compile(PyObject
*self
, PyObject
*args
)
346 int dont_inherit
= 0;
347 int supplied_flags
= 0;
349 PyObject
*result
, *cmd
, *tmp
= NULL
;
352 if (!PyArg_ParseTuple(args
, "Oss|ii:compile", &cmd
, &filename
,
353 &startstr
, &supplied_flags
, &dont_inherit
))
356 cf
.cf_flags
= supplied_flags
;
358 #ifdef Py_USING_UNICODE
359 if (PyUnicode_Check(cmd
)) {
360 tmp
= PyUnicode_AsUTF8String(cmd
);
364 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
367 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
369 if ((size_t)length
!= strlen(str
)) {
370 PyErr_SetString(PyExc_TypeError
,
371 "compile() expected string without null bytes");
375 if (strcmp(startstr
, "exec") == 0)
376 start
= Py_file_input
;
377 else if (strcmp(startstr
, "eval") == 0)
378 start
= Py_eval_input
;
379 else if (strcmp(startstr
, "single") == 0)
380 start
= Py_single_input
;
382 PyErr_SetString(PyExc_ValueError
,
383 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
388 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
))
390 PyErr_SetString(PyExc_ValueError
,
391 "compile(): unrecognised flags");
394 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
397 PyEval_MergeCompilerFlags(&cf
);
399 result
= Py_CompileStringFlags(str
, filename
, start
, &cf
);
404 PyDoc_STRVAR(compile_doc
,
405 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
407 Compile the source string (a Python module, statement or expression)\n\
408 into a code object that can be executed by the exec statement or eval().\n\
409 The filename will be used for run-time error messages.\n\
410 The mode must be 'exec' to compile a module, 'single' to compile a\n\
411 single (interactive) statement, or 'eval' to compile an expression.\n\
412 The flags argument, if present, controls which future statements influence\n\
413 the compilation of the code.\n\
414 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
415 the effects of any future statements in effect in the code calling\n\
416 compile; if absent or zero these statements do influence the compilation,\n\
417 in addition to any features explicitly specified.");
420 builtin_dir(PyObject
*self
, PyObject
*args
)
422 PyObject
*arg
= NULL
;
424 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
426 return PyObject_Dir(arg
);
429 PyDoc_STRVAR(dir_doc
,
430 "dir([object]) -> list of strings\n"
432 "Return an alphabetized list of names comprising (some of) the attributes\n"
433 "of the given object, and of attributes reachable from it:\n"
435 "No argument: the names in the current scope.\n"
436 "Module object: the module attributes.\n"
437 "Type or class object: its attributes, and recursively the attributes of\n"
439 "Otherwise: its attributes, its class's attributes, and recursively the\n"
440 " attributes of its class's base classes.");
443 builtin_divmod(PyObject
*self
, PyObject
*args
)
447 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
449 return PyNumber_Divmod(v
, w
);
452 PyDoc_STRVAR(divmod_doc
,
453 "divmod(x, y) -> (div, mod)\n\
455 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
459 builtin_eval(PyObject
*self
, PyObject
*args
)
461 PyObject
*cmd
, *result
, *tmp
= NULL
;
462 PyObject
*globals
= Py_None
, *locals
= Py_None
;
466 if (!PyArg_ParseTuple(args
, "O|O!O!:eval",
468 &PyDict_Type
, &globals
,
469 &PyDict_Type
, &locals
))
471 if (globals
== Py_None
) {
472 globals
= PyEval_GetGlobals();
473 if (locals
== Py_None
)
474 locals
= PyEval_GetLocals();
476 else if (locals
== Py_None
)
479 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
480 if (PyDict_SetItemString(globals
, "__builtins__",
481 PyEval_GetBuiltins()) != 0)
485 if (PyCode_Check(cmd
)) {
486 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
487 PyErr_SetString(PyExc_TypeError
,
488 "code object passed to eval() may not contain free variables");
491 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
494 if (!PyString_Check(cmd
) &&
495 !PyUnicode_Check(cmd
)) {
496 PyErr_SetString(PyExc_TypeError
,
497 "eval() arg 1 must be a string or code object");
502 #ifdef Py_USING_UNICODE
503 if (PyUnicode_Check(cmd
)) {
504 tmp
= PyUnicode_AsUTF8String(cmd
);
508 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
511 if (PyString_AsStringAndSize(cmd
, &str
, NULL
))
513 while (*str
== ' ' || *str
== '\t')
516 (void)PyEval_MergeCompilerFlags(&cf
);
517 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
522 PyDoc_STRVAR(eval_doc
,
523 "eval(source[, globals[, locals]]) -> value\n\
525 Evaluate the source in the context of globals and locals.\n\
526 The source may be a string representing a Python expression\n\
527 or a code object as returned by compile().\n\
528 The globals and locals are dictionaries, defaulting to the current\n\
529 globals and locals. If only globals is given, locals defaults to it.");
533 builtin_execfile(PyObject
*self
, PyObject
*args
)
536 PyObject
*globals
= Py_None
, *locals
= Py_None
;
542 if (!PyArg_ParseTuple(args
, "s|O!O!:execfile",
544 &PyDict_Type
, &globals
,
545 &PyDict_Type
, &locals
))
547 if (globals
== Py_None
) {
548 globals
= PyEval_GetGlobals();
549 if (locals
== Py_None
)
550 locals
= PyEval_GetLocals();
552 else if (locals
== Py_None
)
554 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
555 if (PyDict_SetItemString(globals
, "__builtins__",
556 PyEval_GetBuiltins()) != 0)
561 /* Test for existence or directory. */
566 if ((d
= dirstat(filename
))!=nil
) {
568 werrstr("is a directory");
574 #elif defined(RISCOS)
575 if (object_exists(filename
)) {
581 #else /* standard Posix */
584 if (stat(filename
, &s
) == 0) {
585 if (S_ISDIR(s
.st_mode
))
586 # if defined(PY_OS2) && defined(PYCC_VACPP)
598 Py_BEGIN_ALLOW_THREADS
599 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
608 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
612 if (PyEval_MergeCompilerFlags(&cf
))
613 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
616 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
621 PyDoc_STRVAR(execfile_doc
,
622 "execfile(filename[, globals[, locals]])\n\
624 Read and execute a Python script from a file.\n\
625 The globals and locals are dictionaries, defaulting to the current\n\
626 globals and locals. If only globals is given, locals defaults to it.");
630 builtin_getattr(PyObject
*self
, PyObject
*args
)
632 PyObject
*v
, *result
, *dflt
= NULL
;
635 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
637 #ifdef Py_USING_UNICODE
638 if (PyUnicode_Check(name
)) {
639 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
645 if (!PyString_Check(name
)) {
646 PyErr_SetString(PyExc_TypeError
,
647 "getattr(): attribute name must be string");
650 result
= PyObject_GetAttr(v
, name
);
651 if (result
== NULL
&& dflt
!= NULL
&&
652 PyErr_ExceptionMatches(PyExc_AttributeError
))
661 PyDoc_STRVAR(getattr_doc
,
662 "getattr(object, name[, default]) -> value\n\
664 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
665 When a default argument is given, it is returned when the attribute doesn't\n\
666 exist; without it, an exception is raised in that case.");
670 builtin_globals(PyObject
*self
)
674 d
= PyEval_GetGlobals();
679 PyDoc_STRVAR(globals_doc
,
680 "globals() -> dictionary\n\
682 Return the dictionary containing the current scope's global variables.");
686 builtin_hasattr(PyObject
*self
, PyObject
*args
)
691 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
693 #ifdef Py_USING_UNICODE
694 if (PyUnicode_Check(name
)) {
695 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
701 if (!PyString_Check(name
)) {
702 PyErr_SetString(PyExc_TypeError
,
703 "hasattr(): attribute name must be string");
706 v
= PyObject_GetAttr(v
, name
);
717 PyDoc_STRVAR(hasattr_doc
,
718 "hasattr(object, name) -> bool\n\
720 Return whether the object has an attribute with the given name.\n\
721 (This is done by calling getattr(object, name) and catching exceptions.)");
725 builtin_id(PyObject
*self
, PyObject
*v
)
727 return PyLong_FromVoidPtr(v
);
731 "id(object) -> integer\n\
733 Return the identity of an object. This is guaranteed to be unique among\n\
734 simultaneously existing objects. (Hint: it's the object's memory address.)");
738 builtin_map(PyObject
*self
, PyObject
*args
)
741 PyObject
*it
; /* the iterator object */
742 int saw_StopIteration
; /* bool: did the iterator end? */
745 PyObject
*func
, *result
;
746 sequence
*seqs
= NULL
, *sqp
;
750 n
= PyTuple_Size(args
);
752 PyErr_SetString(PyExc_TypeError
,
753 "map() requires at least two args");
757 func
= PyTuple_GetItem(args
, 0);
760 if (func
== Py_None
&& n
== 1) {
761 /* map(None, S) is the same as list(S). */
762 return PySequence_List(PyTuple_GetItem(args
, 1));
765 /* Get space for sequence descriptors. Must NULL out the iterator
766 * pointers so that jumping to Fail_2 later doesn't see trash.
768 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
772 for (i
= 0; i
< n
; ++i
) {
773 seqs
[i
].it
= (PyObject
*)NULL
;
774 seqs
[i
].saw_StopIteration
= 0;
777 /* Do a first pass to obtain iterators for the arguments, and set len
778 * to the largest of their lengths.
781 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
786 curseq
= PyTuple_GetItem(args
, i
+1);
787 sqp
->it
= PyObject_GetIter(curseq
);
788 if (sqp
->it
== NULL
) {
789 static char errmsg
[] =
790 "argument %d to map() must support iteration";
791 char errbuf
[sizeof(errmsg
) + 25];
792 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
793 PyErr_SetString(PyExc_TypeError
, errbuf
);
798 curlen
= -1; /* unknown */
799 if (PySequence_Check(curseq
) &&
800 curseq
->ob_type
->tp_as_sequence
->sq_length
) {
801 curlen
= PySequence_Size(curseq
);
806 curlen
= 8; /* arbitrary */
811 /* Get space for the result list. */
812 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
815 /* Iterate over the sequences until all have stopped. */
817 PyObject
*alist
, *item
=NULL
, *value
;
820 if (func
== Py_None
&& n
== 1)
822 else if ((alist
= PyTuple_New(n
)) == NULL
)
825 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
826 if (sqp
->saw_StopIteration
) {
831 item
= PyIter_Next(sqp
->it
);
835 if (PyErr_Occurred()) {
841 sqp
->saw_StopIteration
= 1;
845 PyTuple_SET_ITEM(alist
, j
, item
);
853 if (numactive
== 0) {
861 value
= PyEval_CallObject(func
, alist
);
867 int status
= PyList_Append(result
, value
);
872 else if (PyList_SetItem(result
, i
, value
) < 0)
876 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
887 for (i
= 0; i
< n
; ++i
)
888 Py_XDECREF(seqs
[i
].it
);
893 PyDoc_STRVAR(map_doc
,
894 "map(function, sequence[, sequence, ...]) -> list\n\
896 Return a list of the results of applying the function to the items of\n\
897 the argument sequence(s). If more than one sequence is given, the\n\
898 function is called with an argument list consisting of the corresponding\n\
899 item of each sequence, substituting None for missing values when not all\n\
900 sequences have the same length. If the function is None, return a list of\n\
901 the items of the sequence (or a list of tuples if more than one sequence).");
905 builtin_setattr(PyObject
*self
, PyObject
*args
)
911 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
913 if (PyObject_SetAttr(v
, name
, value
) != 0)
919 PyDoc_STRVAR(setattr_doc
,
920 "setattr(object, name, value)\n\
922 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
927 builtin_delattr(PyObject
*self
, PyObject
*args
)
932 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
934 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
940 PyDoc_STRVAR(delattr_doc
,
941 "delattr(object, name)\n\
943 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
948 builtin_hash(PyObject
*self
, PyObject
*v
)
952 x
= PyObject_Hash(v
);
955 return PyInt_FromLong(x
);
958 PyDoc_STRVAR(hash_doc
,
959 "hash(object) -> integer\n\
961 Return a hash value for the object. Two objects with the same value have\n\
962 the same hash value. The reverse is not necessarily true, but likely.");
966 builtin_hex(PyObject
*self
, PyObject
*v
)
970 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
971 nb
->nb_hex
== NULL
) {
972 PyErr_SetString(PyExc_TypeError
,
973 "hex() argument can't be converted to hex");
976 return (*nb
->nb_hex
)(v
);
979 PyDoc_STRVAR(hex_doc
,
980 "hex(number) -> string\n\
982 Return the hexadecimal representation of an integer or long integer.");
985 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
988 builtin_input(PyObject
*self
, PyObject
*args
)
993 PyObject
*globals
, *locals
;
995 line
= builtin_raw_input(self
, args
);
998 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1000 while (*str
== ' ' || *str
== '\t')
1002 globals
= PyEval_GetGlobals();
1003 locals
= PyEval_GetLocals();
1004 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1005 if (PyDict_SetItemString(globals
, "__builtins__",
1006 PyEval_GetBuiltins()) != 0)
1009 res
= PyRun_String(str
, Py_eval_input
, globals
, locals
);
1014 PyDoc_STRVAR(input_doc
,
1015 "input([prompt]) -> value\n\
1017 Equivalent to eval(raw_input(prompt)).");
1021 builtin_intern(PyObject
*self
, PyObject
*args
)
1024 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1027 PyString_InternInPlace(&s
);
1031 PyDoc_STRVAR(intern_doc
,
1032 "intern(string) -> string\n\
1034 ``Intern'' the given string. This enters the string in the (global)\n\
1035 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1036 Return the string itself or the previously interned string object with the\n\
1041 builtin_iter(PyObject
*self
, PyObject
*args
)
1043 PyObject
*v
, *w
= NULL
;
1045 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1048 return PyObject_GetIter(v
);
1049 if (!PyCallable_Check(v
)) {
1050 PyErr_SetString(PyExc_TypeError
,
1051 "iter(v, w): v must be callable");
1054 return PyCallIter_New(v
, w
);
1057 PyDoc_STRVAR(iter_doc
,
1058 "iter(collection) -> iterator\n\
1059 iter(callable, sentinel) -> iterator\n\
1061 Get an iterator from an object. In the first form, the argument must\n\
1062 supply its own iterator, or be a sequence.\n\
1063 In the second form, the callable is called until it returns the sentinel.");
1067 builtin_len(PyObject
*self
, PyObject
*v
)
1071 res
= PyObject_Size(v
);
1072 if (res
< 0 && PyErr_Occurred())
1074 return PyInt_FromLong(res
);
1077 PyDoc_STRVAR(len_doc
,
1078 "len(object) -> integer\n\
1080 Return the number of items of a sequence or mapping.");
1084 builtin_locals(PyObject
*self
)
1088 d
= PyEval_GetLocals();
1093 PyDoc_STRVAR(locals_doc
,
1094 "locals() -> dictionary\n\
1096 Update and return a dictionary containing the current scope's local variables.");
1100 min_max(PyObject
*args
, int op
)
1102 PyObject
*v
, *w
, *x
, *it
;
1104 if (PyTuple_Size(args
) > 1)
1106 else if (!PyArg_UnpackTuple(args
, (op
==Py_LT
) ? "min" : "max", 1, 1, &v
))
1109 it
= PyObject_GetIter(v
);
1113 w
= NULL
; /* the result */
1115 x
= PyIter_Next(it
);
1117 if (PyErr_Occurred()) {
1128 int cmp
= PyObject_RichCompareBool(x
, w
, op
);
1144 PyErr_SetString(PyExc_ValueError
,
1145 "min() or max() arg is an empty sequence");
1151 builtin_min(PyObject
*self
, PyObject
*v
)
1153 return min_max(v
, Py_LT
);
1156 PyDoc_STRVAR(min_doc
,
1157 "min(sequence) -> value\n\
1158 min(a, b, c, ...) -> value\n\
1160 With a single sequence argument, return its smallest item.\n\
1161 With two or more arguments, return the smallest argument.");
1165 builtin_max(PyObject
*self
, PyObject
*v
)
1167 return min_max(v
, Py_GT
);
1170 PyDoc_STRVAR(max_doc
,
1171 "max(sequence) -> value\n\
1172 max(a, b, c, ...) -> value\n\
1174 With a single sequence argument, return its largest item.\n\
1175 With two or more arguments, return the largest argument.");
1179 builtin_oct(PyObject
*self
, PyObject
*v
)
1181 PyNumberMethods
*nb
;
1183 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1184 nb
->nb_oct
== NULL
) {
1185 PyErr_SetString(PyExc_TypeError
,
1186 "oct() argument can't be converted to oct");
1189 return (*nb
->nb_oct
)(v
);
1192 PyDoc_STRVAR(oct_doc
,
1193 "oct(number) -> string\n\
1195 Return the octal representation of an integer or long integer.");
1199 builtin_ord(PyObject
*self
, PyObject
* obj
)
1204 if (PyString_Check(obj
)) {
1205 size
= PyString_GET_SIZE(obj
);
1207 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1208 return PyInt_FromLong(ord
);
1210 #ifdef Py_USING_UNICODE
1211 } else if (PyUnicode_Check(obj
)) {
1212 size
= PyUnicode_GET_SIZE(obj
);
1214 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1215 return PyInt_FromLong(ord
);
1219 PyErr_Format(PyExc_TypeError
,
1220 "ord() expected string of length 1, but " \
1221 "%.200s found", obj
->ob_type
->tp_name
);
1225 PyErr_Format(PyExc_TypeError
,
1226 "ord() expected a character, "
1227 "but string of length %d found",
1232 PyDoc_STRVAR(ord_doc
,
1233 "ord(c) -> integer\n\
1235 Return the integer ordinal of a one-character string.");
1239 builtin_pow(PyObject
*self
, PyObject
*args
)
1241 PyObject
*v
, *w
, *z
= Py_None
;
1243 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1245 return PyNumber_Power(v
, w
, z
);
1248 PyDoc_STRVAR(pow_doc
,
1249 "pow(x, y[, z]) -> number\n\
1251 With two arguments, equivalent to x**y. With three arguments,\n\
1252 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1256 /* Return number of items in range (lo, hi, step), when arguments are
1257 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1258 * & only if the true value is too large to fit in a signed long.
1259 * Arguments MUST return 1 with either PyInt_Check() or
1260 * PyLong_Check(). Return -1 when there is an error.
1263 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1265 /* -------------------------------------------------------------
1266 Algorithm is equal to that of get_len_of_range(), but it operates
1267 on PyObjects (which are assumed to be PyLong or PyInt objects).
1268 ---------------------------------------------------------------*/
1270 PyObject
*diff
= NULL
;
1271 PyObject
*one
= NULL
;
1272 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1273 /* holds sub-expression evaluations */
1275 /* if (lo >= hi), return length of 0. */
1276 if (PyObject_Compare(lo
, hi
) >= 0)
1279 if ((one
= PyLong_FromLong(1L)) == NULL
)
1282 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1285 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1288 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1291 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1294 n
= PyLong_AsLong(tmp3
);
1295 if (PyErr_Occurred()) { /* Check for Overflow */
1316 /* An extension of builtin_range() that handles the case when PyLong
1317 * arguments are given. */
1319 handle_range_longs(PyObject
*self
, PyObject
*args
)
1322 PyObject
*ihigh
= NULL
;
1323 PyObject
*istep
= NULL
;
1325 PyObject
*curnum
= NULL
;
1331 PyObject
*zero
= PyLong_FromLong(0);
1336 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1341 /* Figure out which way we were called, supply defaults, and be
1342 * sure to incref everything so that the decrefs at the end
1345 assert(ilow
!= NULL
);
1346 if (ihigh
== NULL
) {
1347 /* only 1 arg -- it's the upper limit */
1351 assert(ihigh
!= NULL
);
1354 /* ihigh correct now; do ilow */
1359 /* ilow and ihigh correct now; do istep */
1360 if (istep
== NULL
) {
1361 istep
= PyLong_FromLong(1L);
1369 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1370 PyErr_Format(PyExc_TypeError
,
1371 "range() integer start argument expected, got %s.",
1372 ilow
->ob_type
->tp_name
);
1376 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1377 PyErr_Format(PyExc_TypeError
,
1378 "range() integer end argument expected, got %s.",
1379 ihigh
->ob_type
->tp_name
);
1383 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1384 PyErr_Format(PyExc_TypeError
,
1385 "range() integer step argument expected, got %s.",
1386 istep
->ob_type
->tp_name
);
1390 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1392 if (cmp_result
== 0) {
1393 PyErr_SetString(PyExc_ValueError
,
1394 "range() step argument must not be zero");
1399 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1401 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1402 if (neg_istep
== NULL
)
1404 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1405 Py_DECREF(neg_istep
);
1409 if (bign
< 0 || (long)n
!= bign
) {
1410 PyErr_SetString(PyExc_OverflowError
,
1411 "range() result has too many items");
1422 for (i
= 0; i
< n
; i
++) {
1423 PyObject
*w
= PyNumber_Long(curnum
);
1428 PyList_SET_ITEM(v
, i
, w
);
1430 tmp_num
= PyNumber_Add(curnum
, istep
);
1431 if (tmp_num
== NULL
)
1454 /* Return number of items in range/xrange (lo, hi, step). step > 0
1455 * required. Return a value < 0 if & only if the true value is too
1456 * large to fit in a signed long.
1459 get_len_of_range(long lo
, long hi
, long step
)
1461 /* -------------------------------------------------------------
1462 If lo >= hi, the range is empty.
1463 Else if n values are in the range, the last one is
1464 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1465 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1466 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1467 the RHS is non-negative and so truncation is the same as the
1468 floor. Letting M be the largest positive long, the worst case
1469 for the RHS numerator is hi=M, lo=-M-1, and then
1470 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1471 precision to compute the RHS exactly.
1472 ---------------------------------------------------------------*/
1475 unsigned long uhi
= (unsigned long)hi
;
1476 unsigned long ulo
= (unsigned long)lo
;
1477 unsigned long diff
= uhi
- ulo
- 1;
1478 n
= (long)(diff
/ (unsigned long)step
+ 1);
1484 builtin_range(PyObject
*self
, PyObject
*args
)
1486 long ilow
= 0, ihigh
= 0, istep
= 1;
1492 if (PyTuple_Size(args
) <= 1) {
1493 if (!PyArg_ParseTuple(args
,
1494 "l;range() requires 1-3 int arguments",
1497 return handle_range_longs(self
, args
);
1501 if (!PyArg_ParseTuple(args
,
1502 "ll|l;range() requires 1-3 int arguments",
1503 &ilow
, &ihigh
, &istep
)) {
1505 return handle_range_longs(self
, args
);
1509 PyErr_SetString(PyExc_ValueError
,
1510 "range() step argument must not be zero");
1514 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1516 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1518 if (bign
< 0 || (long)n
!= bign
) {
1519 PyErr_SetString(PyExc_OverflowError
,
1520 "range() result has too many items");
1526 for (i
= 0; i
< n
; i
++) {
1527 PyObject
*w
= PyInt_FromLong(ilow
);
1532 PyList_SET_ITEM(v
, i
, w
);
1538 PyDoc_STRVAR(range_doc
,
1539 "range([start,] stop[, step]) -> list of integers\n\
1541 Return a list containing an arithmetic progression of integers.\n\
1542 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1543 When step is given, it specifies the increment (or decrement).\n\
1544 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1545 These are exactly the valid indices for a list of 4 elements.");
1549 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1552 PyObject
*fin
= PySys_GetObject("stdin");
1553 PyObject
*fout
= PySys_GetObject("stdout");
1555 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1559 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1563 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1566 if (PyFile_SoftSpace(fout
, 0)) {
1567 if (PyFile_WriteString(" ", fout
) != 0)
1570 if (PyFile_Check (fin
) && PyFile_Check (fout
)
1571 && isatty(fileno(PyFile_AsFile(fin
)))
1572 && isatty(fileno(PyFile_AsFile(fout
)))) {
1578 po
= PyObject_Str(v
);
1581 prompt
= PyString_AsString(po
);
1589 s
= PyOS_Readline(PyFile_AsFile (fin
), PyFile_AsFile (fout
),
1593 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1597 PyErr_SetNone(PyExc_EOFError
);
1600 else { /* strip trailing '\n' */
1601 size_t len
= strlen(s
);
1602 if (len
> INT_MAX
) {
1603 PyErr_SetString(PyExc_OverflowError
,
1604 "[raw_]input: input too long");
1608 result
= PyString_FromStringAndSize(s
,
1616 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
1619 return PyFile_GetLine(fin
, -1);
1622 PyDoc_STRVAR(raw_input_doc
,
1623 "raw_input([prompt]) -> string\n\
1625 Read a string from standard input. The trailing newline is stripped.\n\
1626 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1627 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1628 is printed without a trailing newline before reading.");
1632 builtin_reduce(PyObject
*self
, PyObject
*args
)
1634 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1636 if (!PyArg_UnpackTuple(args
, "reduce", 2, 3, &func
, &seq
, &result
))
1641 it
= PyObject_GetIter(seq
);
1643 PyErr_SetString(PyExc_TypeError
,
1644 "reduce() arg 2 must support iteration");
1649 if ((args
= PyTuple_New(2)) == NULL
)
1655 if (args
->ob_refcnt
> 1) {
1657 if ((args
= PyTuple_New(2)) == NULL
)
1661 op2
= PyIter_Next(it
);
1663 if (PyErr_Occurred())
1671 PyTuple_SetItem(args
, 0, result
);
1672 PyTuple_SetItem(args
, 1, op2
);
1673 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1681 PyErr_SetString(PyExc_TypeError
,
1682 "reduce() of empty sequence with no initial value");
1694 PyDoc_STRVAR(reduce_doc
,
1695 "reduce(function, sequence[, initial]) -> value\n\
1697 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1698 from left to right, so as to reduce the sequence to a single value.\n\
1699 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1700 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1701 of the sequence in the calculation, and serves as a default when the\n\
1702 sequence is empty.");
1706 builtin_reload(PyObject
*self
, PyObject
*v
)
1708 return PyImport_ReloadModule(v
);
1711 PyDoc_STRVAR(reload_doc
,
1712 "reload(module) -> module\n\
1714 Reload the module. The module must have been successfully imported before.");
1718 builtin_repr(PyObject
*self
, PyObject
*v
)
1720 return PyObject_Repr(v
);
1723 PyDoc_STRVAR(repr_doc
,
1724 "repr(object) -> string\n\
1726 Return the canonical string representation of the object.\n\
1727 For most object types, eval(repr(object)) == object.");
1731 builtin_round(PyObject
*self
, PyObject
*args
)
1738 if (!PyArg_ParseTuple(args
, "d|i:round", &x
, &ndigits
))
1756 return PyFloat_FromDouble(x
);
1759 PyDoc_STRVAR(round_doc
,
1760 "round(number[, ndigits]) -> floating point number\n\
1762 Round a number to a given precision in decimal digits (default 0 digits).\n\
1763 This always returns a floating point number. Precision may be negative.");
1767 builtin_vars(PyObject
*self
, PyObject
*args
)
1772 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
1775 d
= PyEval_GetLocals();
1777 if (!PyErr_Occurred())
1778 PyErr_SetString(PyExc_SystemError
,
1779 "vars(): no locals!?");
1785 d
= PyObject_GetAttrString(v
, "__dict__");
1787 PyErr_SetString(PyExc_TypeError
,
1788 "vars() argument must have __dict__ attribute");
1795 PyDoc_STRVAR(vars_doc
,
1796 "vars([object]) -> dictionary\n\
1798 Without arguments, equivalent to locals().\n\
1799 With an argument, equivalent to object.__dict__.");
1803 builtin_sum(PyObject
*self
, PyObject
*args
)
1806 PyObject
*result
= NULL
;
1807 PyObject
*temp
, *item
, *iter
;
1809 if (!PyArg_ParseTuple(args
, "O|O:sum", &seq
, &result
))
1812 iter
= PyObject_GetIter(seq
);
1816 if (result
== NULL
) {
1817 result
= PyInt_FromLong(0);
1818 if (result
== NULL
) {
1823 /* reject string values for 'start' parameter */
1824 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
1825 PyErr_SetString(PyExc_TypeError
,
1826 "sum() can't sum strings [use ''.join(seq) instead]");
1834 item
= PyIter_Next(iter
);
1836 /* error, or end-of-sequence */
1837 if (PyErr_Occurred()) {
1843 temp
= PyNumber_Add(result
, item
);
1854 PyDoc_STRVAR(sum_doc
,
1855 "sum(sequence, start=0) -> value\n\
1857 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
1858 of parameter 'start'. When the sequence is empty, returns start.");
1862 builtin_isinstance(PyObject
*self
, PyObject
*args
)
1868 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
1871 retval
= PyObject_IsInstance(inst
, cls
);
1874 return PyBool_FromLong(retval
);
1877 PyDoc_STRVAR(isinstance_doc
,
1878 "isinstance(object, class-or-type-or-tuple) -> bool\n\
1880 Return whether an object is an instance of a class or of a subclass thereof.\n\
1881 With a type as second argument, return whether that is the object's type.\n\
1882 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
1883 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
1887 builtin_issubclass(PyObject
*self
, PyObject
*args
)
1893 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
1896 retval
= PyObject_IsSubclass(derived
, cls
);
1899 return PyBool_FromLong(retval
);
1902 PyDoc_STRVAR(issubclass_doc
,
1903 "issubclass(C, B) -> bool\n\
1905 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
1906 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
1907 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
1911 builtin_zip(PyObject
*self
, PyObject
*args
)
1914 const int itemsize
= PySequence_Length(args
);
1916 PyObject
*itlist
; /* tuple of iterators */
1917 int len
; /* guess at result length */
1920 PyErr_SetString(PyExc_TypeError
,
1921 "zip() requires at least one sequence");
1924 /* args must be a tuple */
1925 assert(PyTuple_Check(args
));
1927 /* Guess at result length: the shortest of the input lengths.
1928 If some argument refuses to say, we refuse to guess too, lest
1929 an argument like xrange(sys.maxint) lead us astray.*/
1930 len
= -1; /* unknown */
1931 for (i
= 0; i
< itemsize
; ++i
) {
1932 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
1933 int thislen
= PySequence_Length(item
);
1939 else if (len
< 0 || thislen
< len
)
1943 /* allocate result list */
1945 len
= 10; /* arbitrary */
1946 if ((ret
= PyList_New(len
)) == NULL
)
1949 /* obtain iterators */
1950 itlist
= PyTuple_New(itemsize
);
1953 for (i
= 0; i
< itemsize
; ++i
) {
1954 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
1955 PyObject
*it
= PyObject_GetIter(item
);
1957 if (PyErr_ExceptionMatches(PyExc_TypeError
))
1958 PyErr_Format(PyExc_TypeError
,
1959 "zip argument #%d must support iteration",
1961 goto Fail_ret_itlist
;
1963 PyTuple_SET_ITEM(itlist
, i
, it
);
1966 /* build result into ret list */
1967 for (i
= 0; ; ++i
) {
1969 PyObject
*next
= PyTuple_New(itemsize
);
1971 goto Fail_ret_itlist
;
1973 for (j
= 0; j
< itemsize
; j
++) {
1974 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
1975 PyObject
*item
= PyIter_Next(it
);
1977 if (PyErr_Occurred()) {
1985 PyTuple_SET_ITEM(next
, j
, item
);
1989 PyList_SET_ITEM(ret
, i
, next
);
1991 int status
= PyList_Append(ret
, next
);
1995 goto Fail_ret_itlist
;
2000 if (ret
!= NULL
&& i
< len
) {
2001 /* The list is too big. */
2002 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2015 PyDoc_STRVAR(zip_doc
,
2016 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2018 Return a list of tuples, where each tuple contains the i-th element\n\
2019 from each of the argument sequences. The returned list is truncated\n\
2020 in length to the length of the shortest argument sequence.");
2023 static PyMethodDef builtin_methods
[] = {
2024 {"__import__", builtin___import__
, METH_VARARGS
, import_doc
},
2025 {"abs", builtin_abs
, METH_O
, abs_doc
},
2026 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2027 {"callable", builtin_callable
, METH_O
, callable_doc
},
2028 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2029 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2030 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2031 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
2032 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2033 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2034 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2035 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2036 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2037 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2038 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2039 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2040 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2041 {"hash", builtin_hash
, METH_O
, hash_doc
},
2042 {"hex", builtin_hex
, METH_O
, hex_doc
},
2043 {"id", builtin_id
, METH_O
, id_doc
},
2044 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2045 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2046 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2047 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2048 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2049 {"len", builtin_len
, METH_O
, len_doc
},
2050 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2051 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2052 {"max", builtin_max
, METH_VARARGS
, max_doc
},
2053 {"min", builtin_min
, METH_VARARGS
, min_doc
},
2054 {"oct", builtin_oct
, METH_O
, oct_doc
},
2055 {"ord", builtin_ord
, METH_O
, ord_doc
},
2056 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2057 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2058 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2059 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2060 {"reload", builtin_reload
, METH_O
, reload_doc
},
2061 {"repr", builtin_repr
, METH_O
, repr_doc
},
2062 {"round", builtin_round
, METH_VARARGS
, round_doc
},
2063 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2064 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2065 #ifdef Py_USING_UNICODE
2066 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2068 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2069 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2073 PyDoc_STRVAR(builtin_doc
,
2074 "Built-in functions, exceptions, and other objects.\n\
2076 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2079 _PyBuiltin_Init(void)
2081 PyObject
*mod
, *dict
, *debug
;
2082 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2083 builtin_doc
, (PyObject
*)NULL
,
2084 PYTHON_API_VERSION
);
2087 dict
= PyModule_GetDict(mod
);
2089 #ifdef Py_TRACE_REFS
2090 /* __builtin__ exposes a number of statically allocated objects
2091 * that, before this code was added in 2.3, never showed up in
2092 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2093 * result, programs leaking references to None and False (etc)
2094 * couldn't be diagnosed by examining sys.getobjects(0).
2096 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2098 #define ADD_TO_ALL(OBJECT) (void)0
2101 #define SETBUILTIN(NAME, OBJECT) \
2102 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2106 SETBUILTIN("None", Py_None
);
2107 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2108 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2109 SETBUILTIN("False", Py_False
);
2110 SETBUILTIN("True", Py_True
);
2111 SETBUILTIN("basestring", &PyBaseString_Type
);
2112 SETBUILTIN("bool", &PyBool_Type
);
2113 SETBUILTIN("buffer", &PyBuffer_Type
);
2114 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2115 #ifndef WITHOUT_COMPLEX
2116 SETBUILTIN("complex", &PyComplex_Type
);
2118 SETBUILTIN("dict", &PyDict_Type
);
2119 SETBUILTIN("enumerate", &PyEnum_Type
);
2120 SETBUILTIN("float", &PyFloat_Type
);
2121 SETBUILTIN("property", &PyProperty_Type
);
2122 SETBUILTIN("int", &PyInt_Type
);
2123 SETBUILTIN("list", &PyList_Type
);
2124 SETBUILTIN("long", &PyLong_Type
);
2125 SETBUILTIN("object", &PyBaseObject_Type
);
2126 SETBUILTIN("slice", &PySlice_Type
);
2127 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2128 SETBUILTIN("str", &PyString_Type
);
2129 SETBUILTIN("super", &PySuper_Type
);
2130 SETBUILTIN("tuple", &PyTuple_Type
);
2131 SETBUILTIN("type", &PyType_Type
);
2132 SETBUILTIN("xrange", &PyRange_Type
);
2134 /* Note that open() is just an alias of file(). */
2135 SETBUILTIN("open", &PyFile_Type
);
2136 SETBUILTIN("file", &PyFile_Type
);
2137 #ifdef Py_USING_UNICODE
2138 SETBUILTIN("unicode", &PyUnicode_Type
);
2140 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2141 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2152 /* Helper for filter(): filter a tuple through a function */
2155 filtertuple(PyObject
*func
, PyObject
*tuple
)
2159 int len
= PyTuple_Size(tuple
);
2162 if (PyTuple_CheckExact(tuple
))
2165 tuple
= PyTuple_New(0);
2169 if ((result
= PyTuple_New(len
)) == NULL
)
2172 for (i
= j
= 0; i
< len
; ++i
) {
2173 PyObject
*item
, *good
;
2176 if (tuple
->ob_type
->tp_as_sequence
&&
2177 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2178 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2180 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2183 if (func
== Py_None
) {
2188 PyObject
*arg
= Py_BuildValue("(O)", item
);
2191 good
= PyEval_CallObject(func
, arg
);
2196 ok
= PyObject_IsTrue(good
);
2200 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2205 if (_PyTuple_Resize(&result
, j
) < 0)
2216 /* Helper for filter(): filter a string through a function */
2219 filterstring(PyObject
*func
, PyObject
*strobj
)
2223 int len
= PyString_Size(strobj
);
2226 if (func
== Py_None
) {
2227 /* If it's a real string we can return the original,
2228 * as no character is ever false and __getitem__
2229 * does return this character. If it's a subclass
2230 * we must go through the __getitem__ loop */
2231 if (PyString_CheckExact(strobj
)) {
2236 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2239 for (i
= j
= 0; i
< len
; ++i
) {
2243 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2246 if (func
==Py_None
) {
2249 PyObject
*arg
, *good
;
2250 arg
= Py_BuildValue("(O)", item
);
2255 good
= PyEval_CallObject(func
, arg
);
2261 ok
= PyObject_IsTrue(good
);
2266 if (!PyString_Check(item
)) {
2267 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2268 " __getitem__ returned different type");
2272 reslen
= PyString_GET_SIZE(item
);
2274 PyString_AS_STRING(result
)[j
++] =
2275 PyString_AS_STRING(item
)[0];
2277 /* do we need more space? */
2278 int need
= j
+ reslen
+ len
-i
-1;
2279 if (need
> outlen
) {
2280 /* overallocate, to avoid reallocations */
2283 if (_PyString_Resize(&result
, need
)) {
2290 PyString_AS_STRING(result
) + j
,
2291 PyString_AS_STRING(item
),
2301 _PyString_Resize(&result
, j
);
2310 #ifdef Py_USING_UNICODE
2311 /* Helper for filter(): filter a Unicode object through a function */
2314 filterunicode(PyObject
*func
, PyObject
*strobj
)
2318 int len
= PyUnicode_GetSize(strobj
);
2321 if (func
== Py_None
) {
2322 /* If it's a real string we can return the original,
2323 * as no character is ever false and __getitem__
2324 * does return this character. If it's a subclass
2325 * we must go through the __getitem__ loop */
2326 if (PyUnicode_CheckExact(strobj
)) {
2331 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2334 for (i
= j
= 0; i
< len
; ++i
) {
2335 PyObject
*item
, *arg
, *good
;
2338 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2341 if (func
== Py_None
) {
2344 arg
= Py_BuildValue("(O)", item
);
2349 good
= PyEval_CallObject(func
, arg
);
2355 ok
= PyObject_IsTrue(good
);
2360 if (!PyUnicode_Check(item
)) {
2361 PyErr_SetString(PyExc_TypeError
, "can't filter unicode to unicode:"
2362 " __getitem__ returned different type");
2366 reslen
= PyUnicode_GET_SIZE(item
);
2368 PyUnicode_AS_UNICODE(result
)[j
++] =
2369 PyUnicode_AS_UNICODE(item
)[0];
2371 /* do we need more space? */
2372 int need
= j
+ reslen
+ len
-i
-1;
2373 if (need
> outlen
) {
2374 /* overallocate, to avoid reallocations */
2377 if (PyUnicode_Resize(&result
, need
)) {
2384 PyUnicode_AS_UNICODE(result
) + j
,
2385 PyUnicode_AS_UNICODE(item
),
2386 reslen
*sizeof(Py_UNICODE
)
2395 PyUnicode_Resize(&result
, j
);