1 /* Built-in functions */
12 #include "unixstuff.h"
15 /* The default encoding used by the platform file system APIs
16 Can remain NULL for all platforms that don't have such a concept
18 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
19 const char *Py_FileSystemDefaultEncoding
= "mbcs";
20 #elif defined(__APPLE__)
21 const char *Py_FileSystemDefaultEncoding
= "utf-8";
23 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
27 static PyObject
*filterstring(PyObject
*, PyObject
*);
28 #ifdef Py_USING_UNICODE
29 static PyObject
*filterunicode(PyObject
*, PyObject
*);
31 static PyObject
*filtertuple (PyObject
*, PyObject
*);
34 builtin___import__(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
36 static char *kwlist
[] = {"name", "globals", "locals", "fromlist",
39 PyObject
*globals
= NULL
;
40 PyObject
*locals
= NULL
;
41 PyObject
*fromlist
= NULL
;
44 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "s|OOOi:__import__",
45 kwlist
, &name
, &globals
, &locals
, &fromlist
, &level
))
47 return PyImport_ImportModuleLevel(name
, globals
, locals
,
51 PyDoc_STRVAR(import_doc
,
52 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
54 Import a module. The globals are only used to determine the context;\n\
55 they are not modified. The locals are currently unused. The fromlist\n\
56 should be a list of names to emulate ``from name import ...'', or an\n\
57 empty list to emulate ``import name''.\n\
58 When importing a module from a package, note that __import__('A.B', ...)\n\
59 returns package A when fromlist is empty, but its submodule B when\n\
60 fromlist is not empty. Level is used to determine whether to perform \n\
61 absolute or relative imports. -1 is the original strategy of attempting\n\
62 both absolute and relative imports, 0 is absolute, a positive number\n\
63 is the number of parent directories to search relative to the current module.");
67 builtin_abs(PyObject
*self
, PyObject
*v
)
69 return PyNumber_Absolute(v
);
73 "abs(number) -> number\n\
75 Return the absolute value of the argument.");
78 builtin_all(PyObject
*self
, PyObject
*v
)
82 it
= PyObject_GetIter(v
);
86 while ((item
= PyIter_Next(it
)) != NULL
) {
87 int cmp
= PyObject_IsTrue(item
);
104 PyDoc_STRVAR(all_doc
,
105 "all(iterable) -> bool\n\
107 Return True if bool(x) is True for all values x in the iterable.");
110 builtin_any(PyObject
*self
, PyObject
*v
)
114 it
= PyObject_GetIter(v
);
118 while ((item
= PyIter_Next(it
)) != NULL
) {
119 int cmp
= PyObject_IsTrue(item
);
131 if (PyErr_Occurred())
136 PyDoc_STRVAR(any_doc
,
137 "any(iterable) -> bool\n\
139 Return True if bool(x) is True for any x in the iterable.");
142 builtin_apply(PyObject
*self
, PyObject
*args
)
144 PyObject
*func
, *alist
= NULL
, *kwdict
= NULL
;
145 PyObject
*t
= NULL
, *retval
= NULL
;
147 if (Py_Py3kWarningFlag
&&
148 PyErr_Warn(PyExc_DeprecationWarning
,
149 "apply() not supported in 3.x") < 0)
152 if (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
155 if (!PyTuple_Check(alist
)) {
156 if (!PySequence_Check(alist
)) {
157 PyErr_Format(PyExc_TypeError
,
158 "apply() arg 2 expected sequence, found %s",
159 alist
->ob_type
->tp_name
);
162 t
= PySequence_Tuple(alist
);
168 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
169 PyErr_Format(PyExc_TypeError
,
170 "apply() arg 3 expected dictionary, found %s",
171 kwdict
->ob_type
->tp_name
);
174 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
180 PyDoc_STRVAR(apply_doc
,
181 "apply(object[, args[, kwargs]]) -> value\n\
183 Call a callable object with positional arguments taken from the tuple args,\n\
184 and keyword arguments taken from the optional dictionary kwargs.\n\
185 Note that classes are callable, as are instances with a __call__() method.\n\
187 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
188 function(*args, **keywords).");
192 builtin_callable(PyObject
*self
, PyObject
*v
)
194 if (Py_Py3kWarningFlag
&&
195 PyErr_Warn(PyExc_DeprecationWarning
,
196 "callable() not supported in 3.x") < 0)
198 return PyBool_FromLong((long)PyCallable_Check(v
));
201 PyDoc_STRVAR(callable_doc
,
202 "callable(object) -> bool\n\
204 Return whether the object is callable (i.e., some kind of function).\n\
205 Note that classes are callable, as are instances with a __call__() method.");
209 builtin_filter(PyObject
*self
, PyObject
*args
)
211 PyObject
*func
, *seq
, *result
, *it
, *arg
;
212 Py_ssize_t len
; /* guess for result list size */
213 register Py_ssize_t j
;
215 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
218 /* Strings and tuples return a result of the same type. */
219 if (PyString_Check(seq
))
220 return filterstring(func
, seq
);
221 #ifdef Py_USING_UNICODE
222 if (PyUnicode_Check(seq
))
223 return filterunicode(func
, seq
);
225 if (PyTuple_Check(seq
))
226 return filtertuple(func
, seq
);
228 /* Pre-allocate argument list tuple. */
229 arg
= PyTuple_New(1);
234 it
= PyObject_GetIter(seq
);
238 /* Guess a result list size. */
239 len
= _PyObject_LengthHint(seq
);
241 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
242 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
246 len
= 8; /* arbitrary */
249 /* Get a result list. */
250 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
251 /* Eww - can modify the list in-place. */
256 result
= PyList_New(len
);
261 /* Build the result list. */
267 item
= PyIter_Next(it
);
269 if (PyErr_Occurred())
274 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
275 ok
= PyObject_IsTrue(item
);
279 PyTuple_SET_ITEM(arg
, 0, item
);
280 good
= PyObject_Call(func
, arg
, NULL
);
281 PyTuple_SET_ITEM(arg
, 0, NULL
);
286 ok
= PyObject_IsTrue(good
);
291 PyList_SET_ITEM(result
, j
, item
);
293 int status
= PyList_Append(result
, item
);
305 /* Cut back result list if len is too big. */
306 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
322 PyDoc_STRVAR(filter_doc
,
323 "filter(function or None, sequence) -> list, tuple, or string\n"
325 "Return those items of sequence for which function(item) is true. If\n"
326 "function is None, return the items that are true. If sequence is a tuple\n"
327 "or string, return the same type, else return a list.");
330 builtin_chr(PyObject
*self
, PyObject
*args
)
335 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
337 if (x
< 0 || x
>= 256) {
338 PyErr_SetString(PyExc_ValueError
,
339 "chr() arg not in range(256)");
343 return PyString_FromStringAndSize(s
, 1);
346 PyDoc_STRVAR(chr_doc
,
347 "chr(i) -> character\n\
349 Return a string of one character with ordinal i; 0 <= i < 256.");
352 #ifdef Py_USING_UNICODE
354 builtin_unichr(PyObject
*self
, PyObject
*args
)
358 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
361 return PyUnicode_FromOrdinal(x
);
364 PyDoc_STRVAR(unichr_doc
,
365 "unichr(i) -> Unicode character\n\
367 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
372 builtin_cmp(PyObject
*self
, PyObject
*args
)
377 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
379 if (PyObject_Cmp(a
, b
, &c
) < 0)
381 return PyInt_FromLong((long)c
);
384 PyDoc_STRVAR(cmp_doc
,
385 "cmp(x, y) -> integer\n\
387 Return negative if x<y, zero if x==y, positive if x>y.");
391 builtin_coerce(PyObject
*self
, PyObject
*args
)
396 if (Py_Py3kWarningFlag
&&
397 PyErr_Warn(PyExc_DeprecationWarning
,
398 "coerce() not supported in 3.x") < 0)
401 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
403 if (PyNumber_Coerce(&v
, &w
) < 0)
405 res
= PyTuple_Pack(2, v
, w
);
411 PyDoc_STRVAR(coerce_doc
,
412 "coerce(x, y) -> (x1, y1)\n\
414 Return a tuple consisting of the two numeric arguments converted to\n\
415 a common type, using the same rules as used by arithmetic operations.\n\
416 If coercion is not possible, raise TypeError.");
419 builtin_compile(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
425 int dont_inherit
= 0;
426 int supplied_flags
= 0;
428 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
430 static char *kwlist
[] = {"source", "filename", "mode", "flags",
431 "dont_inherit", NULL
};
433 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oss|ii:compile",
434 kwlist
, &cmd
, &filename
, &startstr
,
435 &supplied_flags
, &dont_inherit
))
438 cf
.cf_flags
= supplied_flags
;
440 #ifdef Py_USING_UNICODE
441 if (PyUnicode_Check(cmd
)) {
442 tmp
= PyUnicode_AsUTF8String(cmd
);
446 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
449 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
451 if ((size_t)length
!= strlen(str
)) {
452 PyErr_SetString(PyExc_TypeError
,
453 "compile() expected string without null bytes");
457 if (strcmp(startstr
, "exec") == 0)
458 start
= Py_file_input
;
459 else if (strcmp(startstr
, "eval") == 0)
460 start
= Py_eval_input
;
461 else if (strcmp(startstr
, "single") == 0)
462 start
= Py_single_input
;
464 PyErr_SetString(PyExc_ValueError
,
465 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
470 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
472 PyErr_SetString(PyExc_ValueError
,
473 "compile(): unrecognised flags");
476 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
479 PyEval_MergeCompilerFlags(&cf
);
481 result
= Py_CompileStringFlags(str
, filename
, start
, &cf
);
487 PyDoc_STRVAR(compile_doc
,
488 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
490 Compile the source string (a Python module, statement or expression)\n\
491 into a code object that can be executed by the exec statement or eval().\n\
492 The filename will be used for run-time error messages.\n\
493 The mode must be 'exec' to compile a module, 'single' to compile a\n\
494 single (interactive) statement, or 'eval' to compile an expression.\n\
495 The flags argument, if present, controls which future statements influence\n\
496 the compilation of the code.\n\
497 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
498 the effects of any future statements in effect in the code calling\n\
499 compile; if absent or zero these statements do influence the compilation,\n\
500 in addition to any features explicitly specified.");
503 builtin_dir(PyObject
*self
, PyObject
*args
)
505 PyObject
*arg
= NULL
;
507 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
509 return PyObject_Dir(arg
);
512 PyDoc_STRVAR(dir_doc
,
513 "dir([object]) -> list of strings\n"
515 "If called without an argument, return the names in the current scope.\n"
516 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
517 "of the given object, and of attributes reachable from it.\n"
518 "If the object supplies a method named __dir__, it will be used; otherwise\n"
519 "the default dir() logic is used and returns:\n"
520 " for a module object: the module's attributes.\n"
521 " for a class object: its attributes, and recursively the attributes\n"
523 " for any other object: its attributes, its class's attributes, and\n"
524 " recursively the attributes of its class's base classes.");
527 builtin_divmod(PyObject
*self
, PyObject
*args
)
531 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
533 return PyNumber_Divmod(v
, w
);
536 PyDoc_STRVAR(divmod_doc
,
537 "divmod(x, y) -> (div, mod)\n\
539 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
543 builtin_eval(PyObject
*self
, PyObject
*args
)
545 PyObject
*cmd
, *result
, *tmp
= NULL
;
546 PyObject
*globals
= Py_None
, *locals
= Py_None
;
550 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
552 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
553 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
556 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
557 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
558 "globals must be a real dict; try eval(expr, {}, mapping)"
559 : "globals must be a dict");
562 if (globals
== Py_None
) {
563 globals
= PyEval_GetGlobals();
564 if (locals
== Py_None
)
565 locals
= PyEval_GetLocals();
567 else if (locals
== Py_None
)
570 if (globals
== NULL
|| locals
== NULL
) {
571 PyErr_SetString(PyExc_TypeError
,
572 "eval must be given globals and locals "
573 "when called without a frame");
577 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
578 if (PyDict_SetItemString(globals
, "__builtins__",
579 PyEval_GetBuiltins()) != 0)
583 if (PyCode_Check(cmd
)) {
584 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
585 PyErr_SetString(PyExc_TypeError
,
586 "code object passed to eval() may not contain free variables");
589 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
592 if (!PyString_Check(cmd
) &&
593 !PyUnicode_Check(cmd
)) {
594 PyErr_SetString(PyExc_TypeError
,
595 "eval() arg 1 must be a string or code object");
600 #ifdef Py_USING_UNICODE
601 if (PyUnicode_Check(cmd
)) {
602 tmp
= PyUnicode_AsUTF8String(cmd
);
606 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
609 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
613 while (*str
== ' ' || *str
== '\t')
616 (void)PyEval_MergeCompilerFlags(&cf
);
617 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
622 PyDoc_STRVAR(eval_doc
,
623 "eval(source[, globals[, locals]]) -> value\n\
625 Evaluate the source in the context of globals and locals.\n\
626 The source may be a string representing a Python expression\n\
627 or a code object as returned by compile().\n\
628 The globals must be a dictionary and locals can be any mapping,\n\
629 defaulting to the current globals and locals.\n\
630 If only globals is given, locals defaults to it.\n");
634 builtin_execfile(PyObject
*self
, PyObject
*args
)
637 PyObject
*globals
= Py_None
, *locals
= Py_None
;
643 if (Py_Py3kWarningFlag
&&
644 PyErr_Warn(PyExc_DeprecationWarning
,
645 "execfile() not supported in 3.x") < 0)
648 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
650 &PyDict_Type
, &globals
,
653 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
654 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
657 if (globals
== Py_None
) {
658 globals
= PyEval_GetGlobals();
659 if (locals
== Py_None
)
660 locals
= PyEval_GetLocals();
662 else if (locals
== Py_None
)
664 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
665 if (PyDict_SetItemString(globals
, "__builtins__",
666 PyEval_GetBuiltins()) != 0)
671 /* Test for existence or directory. */
676 if ((d
= dirstat(filename
))!=nil
) {
678 werrstr("is a directory");
684 #elif defined(RISCOS)
685 if (object_exists(filename
)) {
691 #else /* standard Posix */
694 if (stat(filename
, &s
) == 0) {
695 if (S_ISDIR(s
.st_mode
))
696 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
708 Py_BEGIN_ALLOW_THREADS
709 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
718 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
722 if (PyEval_MergeCompilerFlags(&cf
))
723 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
726 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
731 PyDoc_STRVAR(execfile_doc
,
732 "execfile(filename[, globals[, locals]])\n\
734 Read and execute a Python script from a file.\n\
735 The globals and locals are dictionaries, defaulting to the current\n\
736 globals and locals. If only globals is given, locals defaults to it.");
740 builtin_getattr(PyObject
*self
, PyObject
*args
)
742 PyObject
*v
, *result
, *dflt
= NULL
;
745 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
747 #ifdef Py_USING_UNICODE
748 if (PyUnicode_Check(name
)) {
749 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
755 if (!PyString_Check(name
)) {
756 PyErr_SetString(PyExc_TypeError
,
757 "getattr(): attribute name must be string");
760 result
= PyObject_GetAttr(v
, name
);
761 if (result
== NULL
&& dflt
!= NULL
&&
762 PyErr_ExceptionMatches(PyExc_AttributeError
))
771 PyDoc_STRVAR(getattr_doc
,
772 "getattr(object, name[, default]) -> value\n\
774 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
775 When a default argument is given, it is returned when the attribute doesn't\n\
776 exist; without it, an exception is raised in that case.");
780 builtin_globals(PyObject
*self
)
784 d
= PyEval_GetGlobals();
789 PyDoc_STRVAR(globals_doc
,
790 "globals() -> dictionary\n\
792 Return the dictionary containing the current scope's global variables.");
796 builtin_hasattr(PyObject
*self
, PyObject
*args
)
801 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
803 #ifdef Py_USING_UNICODE
804 if (PyUnicode_Check(name
)) {
805 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
811 if (!PyString_Check(name
)) {
812 PyErr_SetString(PyExc_TypeError
,
813 "hasattr(): attribute name must be string");
816 v
= PyObject_GetAttr(v
, name
);
827 PyDoc_STRVAR(hasattr_doc
,
828 "hasattr(object, name) -> bool\n\
830 Return whether the object has an attribute with the given name.\n\
831 (This is done by calling getattr(object, name) and catching exceptions.)");
835 builtin_id(PyObject
*self
, PyObject
*v
)
837 return PyLong_FromVoidPtr(v
);
841 "id(object) -> integer\n\
843 Return the identity of an object. This is guaranteed to be unique among\n\
844 simultaneously existing objects. (Hint: it's the object's memory address.)");
848 builtin_map(PyObject
*self
, PyObject
*args
)
851 PyObject
*it
; /* the iterator object */
852 int saw_StopIteration
; /* bool: did the iterator end? */
855 PyObject
*func
, *result
;
856 sequence
*seqs
= NULL
, *sqp
;
860 n
= PyTuple_Size(args
);
862 PyErr_SetString(PyExc_TypeError
,
863 "map() requires at least two args");
867 func
= PyTuple_GetItem(args
, 0);
870 if (func
== Py_None
&& n
== 1) {
871 /* map(None, S) is the same as list(S). */
872 return PySequence_List(PyTuple_GetItem(args
, 1));
875 /* Get space for sequence descriptors. Must NULL out the iterator
876 * pointers so that jumping to Fail_2 later doesn't see trash.
878 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
882 for (i
= 0; i
< n
; ++i
) {
883 seqs
[i
].it
= (PyObject
*)NULL
;
884 seqs
[i
].saw_StopIteration
= 0;
887 /* Do a first pass to obtain iterators for the arguments, and set len
888 * to the largest of their lengths.
891 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
896 curseq
= PyTuple_GetItem(args
, i
+1);
897 sqp
->it
= PyObject_GetIter(curseq
);
898 if (sqp
->it
== NULL
) {
899 static char errmsg
[] =
900 "argument %d to map() must support iteration";
901 char errbuf
[sizeof(errmsg
) + 25];
902 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
903 PyErr_SetString(PyExc_TypeError
, errbuf
);
908 curlen
= _PyObject_LengthHint(curseq
);
910 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
911 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
915 curlen
= 8; /* arbitrary */
921 /* Get space for the result list. */
922 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
925 /* Iterate over the sequences until all have stopped. */
927 PyObject
*alist
, *item
=NULL
, *value
;
930 if (func
== Py_None
&& n
== 1)
932 else if ((alist
= PyTuple_New(n
)) == NULL
)
935 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
936 if (sqp
->saw_StopIteration
) {
941 item
= PyIter_Next(sqp
->it
);
945 if (PyErr_Occurred()) {
951 sqp
->saw_StopIteration
= 1;
955 PyTuple_SET_ITEM(alist
, j
, item
);
963 if (numactive
== 0) {
971 value
= PyEval_CallObject(func
, alist
);
977 int status
= PyList_Append(result
, value
);
982 else if (PyList_SetItem(result
, i
, value
) < 0)
986 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
997 for (i
= 0; i
< n
; ++i
)
998 Py_XDECREF(seqs
[i
].it
);
1003 PyDoc_STRVAR(map_doc
,
1004 "map(function, sequence[, sequence, ...]) -> list\n\
1006 Return a list of the results of applying the function to the items of\n\
1007 the argument sequence(s). If more than one sequence is given, the\n\
1008 function is called with an argument list consisting of the corresponding\n\
1009 item of each sequence, substituting None for missing values when not all\n\
1010 sequences have the same length. If the function is None, return a list of\n\
1011 the items of the sequence (or a list of tuples if more than one sequence).");
1015 builtin_setattr(PyObject
*self
, PyObject
*args
)
1021 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1023 if (PyObject_SetAttr(v
, name
, value
) != 0)
1029 PyDoc_STRVAR(setattr_doc
,
1030 "setattr(object, name, value)\n\
1032 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1037 builtin_delattr(PyObject
*self
, PyObject
*args
)
1042 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1044 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1050 PyDoc_STRVAR(delattr_doc
,
1051 "delattr(object, name)\n\
1053 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1058 builtin_hash(PyObject
*self
, PyObject
*v
)
1062 x
= PyObject_Hash(v
);
1065 return PyInt_FromLong(x
);
1068 PyDoc_STRVAR(hash_doc
,
1069 "hash(object) -> integer\n\
1071 Return a hash value for the object. Two objects with the same value have\n\
1072 the same hash value. The reverse is not necessarily true, but likely.");
1076 builtin_hex(PyObject
*self
, PyObject
*v
)
1078 PyNumberMethods
*nb
;
1081 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1082 nb
->nb_hex
== NULL
) {
1083 PyErr_SetString(PyExc_TypeError
,
1084 "hex() argument can't be converted to hex");
1087 res
= (*nb
->nb_hex
)(v
);
1088 if (res
&& !PyString_Check(res
)) {
1089 PyErr_Format(PyExc_TypeError
,
1090 "__hex__ returned non-string (type %.200s)",
1091 res
->ob_type
->tp_name
);
1098 PyDoc_STRVAR(hex_doc
,
1099 "hex(number) -> string\n\
1101 Return the hexadecimal representation of an integer or long integer.");
1104 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1107 builtin_input(PyObject
*self
, PyObject
*args
)
1112 PyObject
*globals
, *locals
;
1115 line
= builtin_raw_input(self
, args
);
1118 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1120 while (*str
== ' ' || *str
== '\t')
1122 globals
= PyEval_GetGlobals();
1123 locals
= PyEval_GetLocals();
1124 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1125 if (PyDict_SetItemString(globals
, "__builtins__",
1126 PyEval_GetBuiltins()) != 0)
1130 PyEval_MergeCompilerFlags(&cf
);
1131 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1136 PyDoc_STRVAR(input_doc
,
1137 "input([prompt]) -> value\n\
1139 Equivalent to eval(raw_input(prompt)).");
1143 builtin_intern(PyObject
*self
, PyObject
*args
)
1146 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1148 if (!PyString_CheckExact(s
)) {
1149 PyErr_SetString(PyExc_TypeError
,
1150 "can't intern subclass of string");
1154 PyString_InternInPlace(&s
);
1158 PyDoc_STRVAR(intern_doc
,
1159 "intern(string) -> string\n\
1161 ``Intern'' the given string. This enters the string in the (global)\n\
1162 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1163 Return the string itself or the previously interned string object with the\n\
1168 builtin_iter(PyObject
*self
, PyObject
*args
)
1170 PyObject
*v
, *w
= NULL
;
1172 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1175 return PyObject_GetIter(v
);
1176 if (!PyCallable_Check(v
)) {
1177 PyErr_SetString(PyExc_TypeError
,
1178 "iter(v, w): v must be callable");
1181 return PyCallIter_New(v
, w
);
1184 PyDoc_STRVAR(iter_doc
,
1185 "iter(collection) -> iterator\n\
1186 iter(callable, sentinel) -> iterator\n\
1188 Get an iterator from an object. In the first form, the argument must\n\
1189 supply its own iterator, or be a sequence.\n\
1190 In the second form, the callable is called until it returns the sentinel.");
1194 builtin_len(PyObject
*self
, PyObject
*v
)
1198 res
= PyObject_Size(v
);
1199 if (res
< 0 && PyErr_Occurred())
1201 return PyInt_FromSsize_t(res
);
1204 PyDoc_STRVAR(len_doc
,
1205 "len(object) -> integer\n\
1207 Return the number of items of a sequence or mapping.");
1211 builtin_locals(PyObject
*self
)
1215 d
= PyEval_GetLocals();
1220 PyDoc_STRVAR(locals_doc
,
1221 "locals() -> dictionary\n\
1223 Update and return a dictionary containing the current scope's local variables.");
1227 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1229 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1230 const char *name
= op
== Py_LT
? "min" : "max";
1232 if (PyTuple_Size(args
) > 1)
1234 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1237 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1238 keyfunc
= PyDict_GetItemString(kwds
, "key");
1239 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1240 PyErr_Format(PyExc_TypeError
,
1241 "%s() got an unexpected keyword argument", name
);
1246 it
= PyObject_GetIter(v
);
1250 maxitem
= NULL
; /* the result */
1251 maxval
= NULL
; /* the value associated with the result */
1252 while (( item
= PyIter_Next(it
) )) {
1253 /* get the value from the key function */
1254 if (keyfunc
!= NULL
) {
1255 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1259 /* no key function; the value is the item */
1265 /* maximum value and item are unset; set them */
1266 if (maxval
== NULL
) {
1270 /* maximum value and item are set; update them as necessary */
1272 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1274 goto Fail_it_item_and_val
;
1287 if (PyErr_Occurred())
1289 if (maxval
== NULL
) {
1290 PyErr_Format(PyExc_ValueError
,
1291 "%s() arg is an empty sequence", name
);
1292 assert(maxitem
== NULL
);
1299 Fail_it_item_and_val
:
1305 Py_XDECREF(maxitem
);
1311 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1313 return min_max(args
, kwds
, Py_LT
);
1316 PyDoc_STRVAR(min_doc
,
1317 "min(iterable[, key=func]) -> value\n\
1318 min(a, b, c, ...[, key=func]) -> value\n\
1320 With a single iterable argument, return its smallest item.\n\
1321 With two or more arguments, return the smallest argument.");
1325 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1327 return min_max(args
, kwds
, Py_GT
);
1330 PyDoc_STRVAR(max_doc
,
1331 "max(iterable[, key=func]) -> value\n\
1332 max(a, b, c, ...[, key=func]) -> value\n\
1334 With a single iterable argument, return its largest item.\n\
1335 With two or more arguments, return the largest argument.");
1339 builtin_oct(PyObject
*self
, PyObject
*v
)
1341 PyNumberMethods
*nb
;
1344 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1345 nb
->nb_oct
== NULL
) {
1346 PyErr_SetString(PyExc_TypeError
,
1347 "oct() argument can't be converted to oct");
1350 res
= (*nb
->nb_oct
)(v
);
1351 if (res
&& !PyString_Check(res
)) {
1352 PyErr_Format(PyExc_TypeError
,
1353 "__oct__ returned non-string (type %.200s)",
1354 res
->ob_type
->tp_name
);
1361 PyDoc_STRVAR(oct_doc
,
1362 "oct(number) -> string\n\
1364 Return the octal representation of an integer or long integer.");
1368 builtin_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1370 return PyObject_Call((PyObject
*)&PyFile_Type
, args
, kwds
);
1373 PyDoc_STRVAR(open_doc
,
1374 "open(name[, mode[, buffering]]) -> file object\n\
1376 Open a file using the file() type, returns a file object.");
1380 builtin_ord(PyObject
*self
, PyObject
* obj
)
1385 if (PyString_Check(obj
)) {
1386 size
= PyString_GET_SIZE(obj
);
1388 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1389 return PyInt_FromLong(ord
);
1391 #ifdef Py_USING_UNICODE
1392 } else if (PyUnicode_Check(obj
)) {
1393 size
= PyUnicode_GET_SIZE(obj
);
1395 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1396 return PyInt_FromLong(ord
);
1400 PyErr_Format(PyExc_TypeError
,
1401 "ord() expected string of length 1, but " \
1402 "%.200s found", obj
->ob_type
->tp_name
);
1406 PyErr_Format(PyExc_TypeError
,
1407 "ord() expected a character, "
1408 "but string of length %zd found",
1413 PyDoc_STRVAR(ord_doc
,
1414 "ord(c) -> integer\n\
1416 Return the integer ordinal of a one-character string.");
1420 builtin_pow(PyObject
*self
, PyObject
*args
)
1422 PyObject
*v
, *w
, *z
= Py_None
;
1424 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1426 return PyNumber_Power(v
, w
, z
);
1429 PyDoc_STRVAR(pow_doc
,
1430 "pow(x, y[, z]) -> number\n\
1432 With two arguments, equivalent to x**y. With three arguments,\n\
1433 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1437 /* Return number of items in range (lo, hi, step), when arguments are
1438 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1439 * & only if the true value is too large to fit in a signed long.
1440 * Arguments MUST return 1 with either PyInt_Check() or
1441 * PyLong_Check(). Return -1 when there is an error.
1444 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1446 /* -------------------------------------------------------------
1447 Algorithm is equal to that of get_len_of_range(), but it operates
1448 on PyObjects (which are assumed to be PyLong or PyInt objects).
1449 ---------------------------------------------------------------*/
1451 PyObject
*diff
= NULL
;
1452 PyObject
*one
= NULL
;
1453 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1454 /* holds sub-expression evaluations */
1456 /* if (lo >= hi), return length of 0. */
1457 if (PyObject_Compare(lo
, hi
) >= 0)
1460 if ((one
= PyLong_FromLong(1L)) == NULL
)
1463 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1466 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1469 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1472 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1475 n
= PyLong_AsLong(tmp3
);
1476 if (PyErr_Occurred()) { /* Check for Overflow */
1497 /* An extension of builtin_range() that handles the case when PyLong
1498 * arguments are given. */
1500 handle_range_longs(PyObject
*self
, PyObject
*args
)
1503 PyObject
*ihigh
= NULL
;
1504 PyObject
*istep
= NULL
;
1506 PyObject
*curnum
= NULL
;
1512 PyObject
*zero
= PyLong_FromLong(0);
1517 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1522 /* Figure out which way we were called, supply defaults, and be
1523 * sure to incref everything so that the decrefs at the end
1526 assert(ilow
!= NULL
);
1527 if (ihigh
== NULL
) {
1528 /* only 1 arg -- it's the upper limit */
1532 assert(ihigh
!= NULL
);
1535 /* ihigh correct now; do ilow */
1540 /* ilow and ihigh correct now; do istep */
1541 if (istep
== NULL
) {
1542 istep
= PyLong_FromLong(1L);
1550 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1551 PyErr_Format(PyExc_TypeError
,
1552 "range() integer start argument expected, got %s.",
1553 ilow
->ob_type
->tp_name
);
1557 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1558 PyErr_Format(PyExc_TypeError
,
1559 "range() integer end argument expected, got %s.",
1560 ihigh
->ob_type
->tp_name
);
1564 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1565 PyErr_Format(PyExc_TypeError
,
1566 "range() integer step argument expected, got %s.",
1567 istep
->ob_type
->tp_name
);
1571 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1573 if (cmp_result
== 0) {
1574 PyErr_SetString(PyExc_ValueError
,
1575 "range() step argument must not be zero");
1580 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1582 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1583 if (neg_istep
== NULL
)
1585 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1586 Py_DECREF(neg_istep
);
1590 if (bign
< 0 || (long)n
!= bign
) {
1591 PyErr_SetString(PyExc_OverflowError
,
1592 "range() result has too many items");
1603 for (i
= 0; i
< n
; i
++) {
1604 PyObject
*w
= PyNumber_Long(curnum
);
1609 PyList_SET_ITEM(v
, i
, w
);
1611 tmp_num
= PyNumber_Add(curnum
, istep
);
1612 if (tmp_num
== NULL
)
1635 /* Return number of items in range/xrange (lo, hi, step). step > 0
1636 * required. Return a value < 0 if & only if the true value is too
1637 * large to fit in a signed long.
1640 get_len_of_range(long lo
, long hi
, long step
)
1642 /* -------------------------------------------------------------
1643 If lo >= hi, the range is empty.
1644 Else if n values are in the range, the last one is
1645 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1646 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1647 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1648 the RHS is non-negative and so truncation is the same as the
1649 floor. Letting M be the largest positive long, the worst case
1650 for the RHS numerator is hi=M, lo=-M-1, and then
1651 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1652 precision to compute the RHS exactly.
1653 ---------------------------------------------------------------*/
1656 unsigned long uhi
= (unsigned long)hi
;
1657 unsigned long ulo
= (unsigned long)lo
;
1658 unsigned long diff
= uhi
- ulo
- 1;
1659 n
= (long)(diff
/ (unsigned long)step
+ 1);
1665 builtin_range(PyObject
*self
, PyObject
*args
)
1667 long ilow
= 0, ihigh
= 0, istep
= 1;
1673 if (PyTuple_Size(args
) <= 1) {
1674 if (!PyArg_ParseTuple(args
,
1675 "l;range() requires 1-3 int arguments",
1678 return handle_range_longs(self
, args
);
1682 if (!PyArg_ParseTuple(args
,
1683 "ll|l;range() requires 1-3 int arguments",
1684 &ilow
, &ihigh
, &istep
)) {
1686 return handle_range_longs(self
, args
);
1690 PyErr_SetString(PyExc_ValueError
,
1691 "range() step argument must not be zero");
1695 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1697 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1699 if (bign
< 0 || (long)n
!= bign
) {
1700 PyErr_SetString(PyExc_OverflowError
,
1701 "range() result has too many items");
1707 for (i
= 0; i
< n
; i
++) {
1708 PyObject
*w
= PyInt_FromLong(ilow
);
1713 PyList_SET_ITEM(v
, i
, w
);
1719 PyDoc_STRVAR(range_doc
,
1720 "range([start,] stop[, step]) -> list of integers\n\
1722 Return a list containing an arithmetic progression of integers.\n\
1723 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1724 When step is given, it specifies the increment (or decrement).\n\
1725 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1726 These are exactly the valid indices for a list of 4 elements.");
1730 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1733 PyObject
*fin
= PySys_GetObject("stdin");
1734 PyObject
*fout
= PySys_GetObject("stdout");
1736 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1740 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1744 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1747 if (PyFile_SoftSpace(fout
, 0)) {
1748 if (PyFile_WriteString(" ", fout
) != 0)
1751 if (PyFile_AsFile(fin
) && PyFile_AsFile(fout
)
1752 && isatty(fileno(PyFile_AsFile(fin
)))
1753 && isatty(fileno(PyFile_AsFile(fout
)))) {
1759 po
= PyObject_Str(v
);
1762 prompt
= PyString_AsString(po
);
1770 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
1774 if (!PyErr_Occurred())
1775 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1779 PyErr_SetNone(PyExc_EOFError
);
1782 else { /* strip trailing '\n' */
1783 size_t len
= strlen(s
);
1784 if (len
> PY_SSIZE_T_MAX
) {
1785 PyErr_SetString(PyExc_OverflowError
,
1786 "[raw_]input: input too long");
1790 result
= PyString_FromStringAndSize(s
, len
-1);
1797 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
1800 return PyFile_GetLine(fin
, -1);
1803 PyDoc_STRVAR(raw_input_doc
,
1804 "raw_input([prompt]) -> string\n\
1806 Read a string from standard input. The trailing newline is stripped.\n\
1807 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1808 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1809 is printed without a trailing newline before reading.");
1813 builtin_reduce(PyObject
*self
, PyObject
*args
)
1815 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1817 if (Py_Py3kWarningFlag
&&
1818 PyErr_Warn(PyExc_DeprecationWarning
,
1819 "reduce() not supported in 3.x") < 0)
1822 if (!PyArg_UnpackTuple(args
, "reduce", 2, 3, &func
, &seq
, &result
))
1827 it
= PyObject_GetIter(seq
);
1829 PyErr_SetString(PyExc_TypeError
,
1830 "reduce() arg 2 must support iteration");
1835 if ((args
= PyTuple_New(2)) == NULL
)
1841 if (args
->ob_refcnt
> 1) {
1843 if ((args
= PyTuple_New(2)) == NULL
)
1847 op2
= PyIter_Next(it
);
1849 if (PyErr_Occurred())
1857 PyTuple_SetItem(args
, 0, result
);
1858 PyTuple_SetItem(args
, 1, op2
);
1859 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1867 PyErr_SetString(PyExc_TypeError
,
1868 "reduce() of empty sequence with no initial value");
1880 PyDoc_STRVAR(reduce_doc
,
1881 "reduce(function, sequence[, initial]) -> value\n\
1883 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1884 from left to right, so as to reduce the sequence to a single value.\n\
1885 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1886 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1887 of the sequence in the calculation, and serves as a default when the\n\
1888 sequence is empty.");
1892 builtin_reload(PyObject
*self
, PyObject
*v
)
1894 if (Py_Py3kWarningFlag
&&
1895 PyErr_Warn(PyExc_DeprecationWarning
,
1896 "reload() not supported in 3.x") < 0)
1899 return PyImport_ReloadModule(v
);
1902 PyDoc_STRVAR(reload_doc
,
1903 "reload(module) -> module\n\
1905 Reload the module. The module must have been successfully imported before.");
1909 builtin_repr(PyObject
*self
, PyObject
*v
)
1911 return PyObject_Repr(v
);
1914 PyDoc_STRVAR(repr_doc
,
1915 "repr(object) -> string\n\
1917 Return the canonical string representation of the object.\n\
1918 For most object types, eval(repr(object)) == object.");
1922 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1928 static char *kwlist
[] = {"number", "ndigits", 0};
1930 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "d|i:round",
1931 kwlist
, &number
, &ndigits
))
1942 number
= floor(number
+ 0.5);
1944 number
= ceil(number
- 0.5);
1949 return PyFloat_FromDouble(number
);
1952 PyDoc_STRVAR(round_doc
,
1953 "round(number[, ndigits]) -> floating point number\n\
1955 Round a number to a given precision in decimal digits (default 0 digits).\n\
1956 This always returns a floating point number. Precision may be negative.");
1959 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1961 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
1963 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
1966 /* args 1-4 should match listsort in Objects/listobject.c */
1967 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
1968 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
1971 newlist
= PySequence_List(seq
);
1972 if (newlist
== NULL
)
1975 callable
= PyObject_GetAttrString(newlist
, "sort");
1976 if (callable
== NULL
) {
1981 newargs
= PyTuple_GetSlice(args
, 1, 4);
1982 if (newargs
== NULL
) {
1984 Py_DECREF(callable
);
1988 v
= PyObject_Call(callable
, newargs
, kwds
);
1990 Py_DECREF(callable
);
1999 PyDoc_STRVAR(sorted_doc
,
2000 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
2003 builtin_vars(PyObject
*self
, PyObject
*args
)
2008 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
2011 d
= PyEval_GetLocals();
2013 if (!PyErr_Occurred())
2014 PyErr_SetString(PyExc_SystemError
,
2015 "vars(): no locals!?");
2021 d
= PyObject_GetAttrString(v
, "__dict__");
2023 PyErr_SetString(PyExc_TypeError
,
2024 "vars() argument must have __dict__ attribute");
2031 PyDoc_STRVAR(vars_doc
,
2032 "vars([object]) -> dictionary\n\
2034 Without arguments, equivalent to locals().\n\
2035 With an argument, equivalent to object.__dict__.");
2039 builtin_sum(PyObject
*self
, PyObject
*args
)
2042 PyObject
*result
= NULL
;
2043 PyObject
*temp
, *item
, *iter
;
2045 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
2048 iter
= PyObject_GetIter(seq
);
2052 if (result
== NULL
) {
2053 result
= PyInt_FromLong(0);
2054 if (result
== NULL
) {
2059 /* reject string values for 'start' parameter */
2060 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2061 PyErr_SetString(PyExc_TypeError
,
2062 "sum() can't sum strings [use ''.join(seq) instead]");
2070 item
= PyIter_Next(iter
);
2072 /* error, or end-of-sequence */
2073 if (PyErr_Occurred()) {
2079 temp
= PyNumber_Add(result
, item
);
2090 PyDoc_STRVAR(sum_doc
,
2091 "sum(sequence[, start]) -> value\n\
2093 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2094 of parameter 'start' (which defaults to 0). When the sequence is\n\
2095 empty, returns start.");
2099 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2105 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2108 retval
= PyObject_IsInstance(inst
, cls
);
2111 return PyBool_FromLong(retval
);
2114 PyDoc_STRVAR(isinstance_doc
,
2115 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2117 Return whether an object is an instance of a class or of a subclass thereof.\n\
2118 With a type as second argument, return whether that is the object's type.\n\
2119 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2120 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2124 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2130 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2133 retval
= PyObject_IsSubclass(derived
, cls
);
2136 return PyBool_FromLong(retval
);
2139 PyDoc_STRVAR(issubclass_doc
,
2140 "issubclass(C, B) -> bool\n\
2142 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2143 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2144 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2148 builtin_zip(PyObject
*self
, PyObject
*args
)
2151 const Py_ssize_t itemsize
= PySequence_Length(args
);
2153 PyObject
*itlist
; /* tuple of iterators */
2154 Py_ssize_t len
; /* guess at result length */
2157 return PyList_New(0);
2159 /* args must be a tuple */
2160 assert(PyTuple_Check(args
));
2162 /* Guess at result length: the shortest of the input lengths.
2163 If some argument refuses to say, we refuse to guess too, lest
2164 an argument like xrange(sys.maxint) lead us astray.*/
2165 len
= -1; /* unknown */
2166 for (i
= 0; i
< itemsize
; ++i
) {
2167 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2168 Py_ssize_t thislen
= _PyObject_LengthHint(item
);
2170 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
2171 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
2178 else if (len
< 0 || thislen
< len
)
2182 /* allocate result list */
2184 len
= 10; /* arbitrary */
2185 if ((ret
= PyList_New(len
)) == NULL
)
2188 /* obtain iterators */
2189 itlist
= PyTuple_New(itemsize
);
2192 for (i
= 0; i
< itemsize
; ++i
) {
2193 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2194 PyObject
*it
= PyObject_GetIter(item
);
2196 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2197 PyErr_Format(PyExc_TypeError
,
2198 "zip argument #%zd must support iteration",
2200 goto Fail_ret_itlist
;
2202 PyTuple_SET_ITEM(itlist
, i
, it
);
2205 /* build result into ret list */
2206 for (i
= 0; ; ++i
) {
2208 PyObject
*next
= PyTuple_New(itemsize
);
2210 goto Fail_ret_itlist
;
2212 for (j
= 0; j
< itemsize
; j
++) {
2213 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2214 PyObject
*item
= PyIter_Next(it
);
2216 if (PyErr_Occurred()) {
2224 PyTuple_SET_ITEM(next
, j
, item
);
2228 PyList_SET_ITEM(ret
, i
, next
);
2230 int status
= PyList_Append(ret
, next
);
2234 goto Fail_ret_itlist
;
2239 if (ret
!= NULL
&& i
< len
) {
2240 /* The list is too big. */
2241 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2254 PyDoc_STRVAR(zip_doc
,
2255 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2257 Return a list of tuples, where each tuple contains the i-th element\n\
2258 from each of the argument sequences. The returned list is truncated\n\
2259 in length to the length of the shortest argument sequence.");
2262 static PyMethodDef builtin_methods
[] = {
2263 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2264 {"abs", builtin_abs
, METH_O
, abs_doc
},
2265 {"all", builtin_all
, METH_O
, all_doc
},
2266 {"any", builtin_any
, METH_O
, any_doc
},
2267 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2268 {"callable", builtin_callable
, METH_O
, callable_doc
},
2269 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2270 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2271 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2272 {"compile", (PyCFunction
)builtin_compile
, METH_VARARGS
| METH_KEYWORDS
, compile_doc
},
2273 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2274 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2275 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2276 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2277 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2278 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2279 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2280 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2281 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2282 {"hash", builtin_hash
, METH_O
, hash_doc
},
2283 {"hex", builtin_hex
, METH_O
, hex_doc
},
2284 {"id", builtin_id
, METH_O
, id_doc
},
2285 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2286 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2287 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2288 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2289 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2290 {"len", builtin_len
, METH_O
, len_doc
},
2291 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2292 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2293 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2294 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2295 {"oct", builtin_oct
, METH_O
, oct_doc
},
2296 {"open", (PyCFunction
)builtin_open
, METH_VARARGS
| METH_KEYWORDS
, open_doc
},
2297 {"ord", builtin_ord
, METH_O
, ord_doc
},
2298 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2299 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2300 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2301 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2302 {"reload", builtin_reload
, METH_O
, reload_doc
},
2303 {"repr", builtin_repr
, METH_O
, repr_doc
},
2304 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2305 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2306 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2307 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2308 #ifdef Py_USING_UNICODE
2309 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2311 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2312 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2316 PyDoc_STRVAR(builtin_doc
,
2317 "Built-in functions, exceptions, and other objects.\n\
2319 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2322 _PyBuiltin_Init(void)
2324 PyObject
*mod
, *dict
, *debug
;
2325 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2326 builtin_doc
, (PyObject
*)NULL
,
2327 PYTHON_API_VERSION
);
2330 dict
= PyModule_GetDict(mod
);
2332 #ifdef Py_TRACE_REFS
2333 /* __builtin__ exposes a number of statically allocated objects
2334 * that, before this code was added in 2.3, never showed up in
2335 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2336 * result, programs leaking references to None and False (etc)
2337 * couldn't be diagnosed by examining sys.getobjects(0).
2339 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2341 #define ADD_TO_ALL(OBJECT) (void)0
2344 #define SETBUILTIN(NAME, OBJECT) \
2345 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2349 SETBUILTIN("None", Py_None
);
2350 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2351 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2352 SETBUILTIN("False", Py_False
);
2353 SETBUILTIN("True", Py_True
);
2354 SETBUILTIN("basestring", &PyBaseString_Type
);
2355 SETBUILTIN("bool", &PyBool_Type
);
2356 SETBUILTIN("buffer", &PyBuffer_Type
);
2357 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2358 #ifndef WITHOUT_COMPLEX
2359 SETBUILTIN("complex", &PyComplex_Type
);
2361 SETBUILTIN("dict", &PyDict_Type
);
2362 SETBUILTIN("enumerate", &PyEnum_Type
);
2363 SETBUILTIN("file", &PyFile_Type
);
2364 SETBUILTIN("float", &PyFloat_Type
);
2365 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2366 SETBUILTIN("property", &PyProperty_Type
);
2367 SETBUILTIN("int", &PyInt_Type
);
2368 SETBUILTIN("list", &PyList_Type
);
2369 SETBUILTIN("long", &PyLong_Type
);
2370 SETBUILTIN("object", &PyBaseObject_Type
);
2371 SETBUILTIN("reversed", &PyReversed_Type
);
2372 SETBUILTIN("set", &PySet_Type
);
2373 SETBUILTIN("slice", &PySlice_Type
);
2374 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2375 SETBUILTIN("str", &PyString_Type
);
2376 SETBUILTIN("super", &PySuper_Type
);
2377 SETBUILTIN("tuple", &PyTuple_Type
);
2378 SETBUILTIN("type", &PyType_Type
);
2379 SETBUILTIN("xrange", &PyRange_Type
);
2380 #ifdef Py_USING_UNICODE
2381 SETBUILTIN("unicode", &PyUnicode_Type
);
2383 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2384 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2395 /* Helper for filter(): filter a tuple through a function */
2398 filtertuple(PyObject
*func
, PyObject
*tuple
)
2402 Py_ssize_t len
= PyTuple_Size(tuple
);
2405 if (PyTuple_CheckExact(tuple
))
2408 tuple
= PyTuple_New(0);
2412 if ((result
= PyTuple_New(len
)) == NULL
)
2415 for (i
= j
= 0; i
< len
; ++i
) {
2416 PyObject
*item
, *good
;
2419 if (tuple
->ob_type
->tp_as_sequence
&&
2420 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2421 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2425 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2428 if (func
== Py_None
) {
2433 PyObject
*arg
= PyTuple_Pack(1, item
);
2438 good
= PyEval_CallObject(func
, arg
);
2445 ok
= PyObject_IsTrue(good
);
2448 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2455 if (_PyTuple_Resize(&result
, j
) < 0)
2466 /* Helper for filter(): filter a string through a function */
2469 filterstring(PyObject
*func
, PyObject
*strobj
)
2473 Py_ssize_t len
= PyString_Size(strobj
);
2474 Py_ssize_t outlen
= len
;
2476 if (func
== Py_None
) {
2477 /* If it's a real string we can return the original,
2478 * as no character is ever false and __getitem__
2479 * does return this character. If it's a subclass
2480 * we must go through the __getitem__ loop */
2481 if (PyString_CheckExact(strobj
)) {
2486 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2489 for (i
= j
= 0; i
< len
; ++i
) {
2493 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2496 if (func
==Py_None
) {
2499 PyObject
*arg
, *good
;
2500 arg
= PyTuple_Pack(1, item
);
2505 good
= PyEval_CallObject(func
, arg
);
2511 ok
= PyObject_IsTrue(good
);
2516 if (!PyString_Check(item
)) {
2517 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2518 " __getitem__ returned different type");
2522 reslen
= PyString_GET_SIZE(item
);
2524 PyString_AS_STRING(result
)[j
++] =
2525 PyString_AS_STRING(item
)[0];
2527 /* do we need more space? */
2528 Py_ssize_t need
= j
+ reslen
+ len
-i
-1;
2529 if (need
> outlen
) {
2530 /* overallocate, to avoid reallocations */
2533 if (_PyString_Resize(&result
, need
)) {
2540 PyString_AS_STRING(result
) + j
,
2541 PyString_AS_STRING(item
),
2551 _PyString_Resize(&result
, j
);
2560 #ifdef Py_USING_UNICODE
2561 /* Helper for filter(): filter a Unicode object through a function */
2564 filterunicode(PyObject
*func
, PyObject
*strobj
)
2567 register Py_ssize_t i
, j
;
2568 Py_ssize_t len
= PyUnicode_GetSize(strobj
);
2569 Py_ssize_t outlen
= len
;
2571 if (func
== Py_None
) {
2572 /* If it's a real string we can return the original,
2573 * as no character is ever false and __getitem__
2574 * does return this character. If it's a subclass
2575 * we must go through the __getitem__ loop */
2576 if (PyUnicode_CheckExact(strobj
)) {
2581 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2584 for (i
= j
= 0; i
< len
; ++i
) {
2585 PyObject
*item
, *arg
, *good
;
2588 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2591 if (func
== Py_None
) {
2594 arg
= PyTuple_Pack(1, item
);
2599 good
= PyEval_CallObject(func
, arg
);
2605 ok
= PyObject_IsTrue(good
);
2610 if (!PyUnicode_Check(item
)) {
2611 PyErr_SetString(PyExc_TypeError
,
2612 "can't filter unicode to unicode:"
2613 " __getitem__ returned different type");
2617 reslen
= PyUnicode_GET_SIZE(item
);
2619 PyUnicode_AS_UNICODE(result
)[j
++] =
2620 PyUnicode_AS_UNICODE(item
)[0];
2622 /* do we need more space? */
2623 Py_ssize_t need
= j
+ reslen
+ len
- i
- 1;
2624 if (need
> outlen
) {
2626 to avoid reallocations */
2627 if (need
< 2 * outlen
)
2629 if (PyUnicode_Resize(
2630 &result
, need
) < 0) {
2636 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2637 PyUnicode_AS_UNICODE(item
),
2638 reslen
*sizeof(Py_UNICODE
));
2646 PyUnicode_Resize(&result
, j
);