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 (!PyArg_UnpackTuple(args
, "apply", 1, 3, &func
, &alist
, &kwdict
))
150 if (!PyTuple_Check(alist
)) {
151 if (!PySequence_Check(alist
)) {
152 PyErr_Format(PyExc_TypeError
,
153 "apply() arg 2 expected sequence, found %s",
154 alist
->ob_type
->tp_name
);
157 t
= PySequence_Tuple(alist
);
163 if (kwdict
!= NULL
&& !PyDict_Check(kwdict
)) {
164 PyErr_Format(PyExc_TypeError
,
165 "apply() arg 3 expected dictionary, found %s",
166 kwdict
->ob_type
->tp_name
);
169 retval
= PyEval_CallObjectWithKeywords(func
, alist
, kwdict
);
175 PyDoc_STRVAR(apply_doc
,
176 "apply(object[, args[, kwargs]]) -> value\n\
178 Call a callable object with positional arguments taken from the tuple args,\n\
179 and keyword arguments taken from the optional dictionary kwargs.\n\
180 Note that classes are callable, as are instances with a __call__() method.\n\
182 Deprecated since release 2.3. Instead, use the extended call syntax:\n\
183 function(*args, **keywords).");
187 builtin_callable(PyObject
*self
, PyObject
*v
)
189 return PyBool_FromLong((long)PyCallable_Check(v
));
192 PyDoc_STRVAR(callable_doc
,
193 "callable(object) -> bool\n\
195 Return whether the object is callable (i.e., some kind of function).\n\
196 Note that classes are callable, as are instances with a __call__() method.");
200 builtin_filter(PyObject
*self
, PyObject
*args
)
202 PyObject
*func
, *seq
, *result
, *it
, *arg
;
203 Py_ssize_t len
; /* guess for result list size */
204 register Py_ssize_t j
;
206 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
209 /* Strings and tuples return a result of the same type. */
210 if (PyString_Check(seq
))
211 return filterstring(func
, seq
);
212 #ifdef Py_USING_UNICODE
213 if (PyUnicode_Check(seq
))
214 return filterunicode(func
, seq
);
216 if (PyTuple_Check(seq
))
217 return filtertuple(func
, seq
);
219 /* Pre-allocate argument list tuple. */
220 arg
= PyTuple_New(1);
225 it
= PyObject_GetIter(seq
);
229 /* Guess a result list size. */
230 len
= _PyObject_LengthHint(seq
);
232 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
233 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
237 len
= 8; /* arbitrary */
240 /* Get a result list. */
241 if (PyList_Check(seq
) && seq
->ob_refcnt
== 1) {
242 /* Eww - can modify the list in-place. */
247 result
= PyList_New(len
);
252 /* Build the result list. */
258 item
= PyIter_Next(it
);
260 if (PyErr_Occurred())
265 if (func
== (PyObject
*)&PyBool_Type
|| func
== Py_None
) {
266 ok
= PyObject_IsTrue(item
);
270 PyTuple_SET_ITEM(arg
, 0, item
);
271 good
= PyObject_Call(func
, arg
, NULL
);
272 PyTuple_SET_ITEM(arg
, 0, NULL
);
277 ok
= PyObject_IsTrue(good
);
282 PyList_SET_ITEM(result
, j
, item
);
284 int status
= PyList_Append(result
, item
);
296 /* Cut back result list if len is too big. */
297 if (j
< len
&& PyList_SetSlice(result
, j
, len
, NULL
) < 0)
313 PyDoc_STRVAR(filter_doc
,
314 "filter(function or None, sequence) -> list, tuple, or string\n"
316 "Return those items of sequence for which function(item) is true. If\n"
317 "function is None, return the items that are true. If sequence is a tuple\n"
318 "or string, return the same type, else return a list.");
321 builtin_chr(PyObject
*self
, PyObject
*args
)
326 if (!PyArg_ParseTuple(args
, "l:chr", &x
))
328 if (x
< 0 || x
>= 256) {
329 PyErr_SetString(PyExc_ValueError
,
330 "chr() arg not in range(256)");
334 return PyString_FromStringAndSize(s
, 1);
337 PyDoc_STRVAR(chr_doc
,
338 "chr(i) -> character\n\
340 Return a string of one character with ordinal i; 0 <= i < 256.");
343 #ifdef Py_USING_UNICODE
345 builtin_unichr(PyObject
*self
, PyObject
*args
)
349 if (!PyArg_ParseTuple(args
, "l:unichr", &x
))
352 return PyUnicode_FromOrdinal(x
);
355 PyDoc_STRVAR(unichr_doc
,
356 "unichr(i) -> Unicode character\n\
358 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
363 builtin_cmp(PyObject
*self
, PyObject
*args
)
368 if (!PyArg_UnpackTuple(args
, "cmp", 2, 2, &a
, &b
))
370 if (PyObject_Cmp(a
, b
, &c
) < 0)
372 return PyInt_FromLong((long)c
);
375 PyDoc_STRVAR(cmp_doc
,
376 "cmp(x, y) -> integer\n\
378 Return negative if x<y, zero if x==y, positive if x>y.");
382 builtin_coerce(PyObject
*self
, PyObject
*args
)
387 if (!PyArg_UnpackTuple(args
, "coerce", 2, 2, &v
, &w
))
389 if (PyNumber_Coerce(&v
, &w
) < 0)
391 res
= PyTuple_Pack(2, v
, w
);
397 PyDoc_STRVAR(coerce_doc
,
398 "coerce(x, y) -> (x1, y1)\n\
400 Return a tuple consisting of the two numeric arguments converted to\n\
401 a common type, using the same rules as used by arithmetic operations.\n\
402 If coercion is not possible, raise TypeError.");
405 builtin_compile(PyObject
*self
, PyObject
*args
)
411 int dont_inherit
= 0;
412 int supplied_flags
= 0;
414 PyObject
*result
= NULL
, *cmd
, *tmp
= NULL
;
417 if (!PyArg_ParseTuple(args
, "Oss|ii:compile", &cmd
, &filename
,
418 &startstr
, &supplied_flags
, &dont_inherit
))
421 cf
.cf_flags
= supplied_flags
;
423 #ifdef Py_USING_UNICODE
424 if (PyUnicode_Check(cmd
)) {
425 tmp
= PyUnicode_AsUTF8String(cmd
);
429 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
432 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &length
))
434 if ((size_t)length
!= strlen(str
)) {
435 PyErr_SetString(PyExc_TypeError
,
436 "compile() expected string without null bytes");
440 if (strcmp(startstr
, "exec") == 0)
441 start
= Py_file_input
;
442 else if (strcmp(startstr
, "eval") == 0)
443 start
= Py_eval_input
;
444 else if (strcmp(startstr
, "single") == 0)
445 start
= Py_single_input
;
447 PyErr_SetString(PyExc_ValueError
,
448 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
453 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
455 PyErr_SetString(PyExc_ValueError
,
456 "compile(): unrecognised flags");
459 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
462 PyEval_MergeCompilerFlags(&cf
);
464 result
= Py_CompileStringFlags(str
, filename
, start
, &cf
);
470 PyDoc_STRVAR(compile_doc
,
471 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
473 Compile the source string (a Python module, statement or expression)\n\
474 into a code object that can be executed by the exec statement or eval().\n\
475 The filename will be used for run-time error messages.\n\
476 The mode must be 'exec' to compile a module, 'single' to compile a\n\
477 single (interactive) statement, or 'eval' to compile an expression.\n\
478 The flags argument, if present, controls which future statements influence\n\
479 the compilation of the code.\n\
480 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
481 the effects of any future statements in effect in the code calling\n\
482 compile; if absent or zero these statements do influence the compilation,\n\
483 in addition to any features explicitly specified.");
486 builtin_dir(PyObject
*self
, PyObject
*args
)
488 PyObject
*arg
= NULL
;
490 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
492 return PyObject_Dir(arg
);
495 PyDoc_STRVAR(dir_doc
,
496 "dir([object]) -> list of strings\n"
498 "Return an alphabetized list of names comprising (some of) the attributes\n"
499 "of the given object, and of attributes reachable from it:\n"
501 "No argument: the names in the current scope.\n"
502 "Module object: the module attributes.\n"
503 "Type or class object: its attributes, and recursively the attributes of\n"
505 "Otherwise: its attributes, its class's attributes, and recursively the\n"
506 " attributes of its class's base classes.");
509 builtin_divmod(PyObject
*self
, PyObject
*args
)
513 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
515 return PyNumber_Divmod(v
, w
);
518 PyDoc_STRVAR(divmod_doc
,
519 "divmod(x, y) -> (div, mod)\n\
521 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
525 builtin_eval(PyObject
*self
, PyObject
*args
)
527 PyObject
*cmd
, *result
, *tmp
= NULL
;
528 PyObject
*globals
= Py_None
, *locals
= Py_None
;
532 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
534 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
535 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
538 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
539 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
540 "globals must be a real dict; try eval(expr, {}, mapping)"
541 : "globals must be a dict");
544 if (globals
== Py_None
) {
545 globals
= PyEval_GetGlobals();
546 if (locals
== Py_None
)
547 locals
= PyEval_GetLocals();
549 else if (locals
== Py_None
)
552 if (globals
== NULL
|| locals
== NULL
) {
553 PyErr_SetString(PyExc_TypeError
,
554 "eval must be given globals and locals "
555 "when called without a frame");
559 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
560 if (PyDict_SetItemString(globals
, "__builtins__",
561 PyEval_GetBuiltins()) != 0)
565 if (PyCode_Check(cmd
)) {
566 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
567 PyErr_SetString(PyExc_TypeError
,
568 "code object passed to eval() may not contain free variables");
571 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
574 if (!PyString_Check(cmd
) &&
575 !PyUnicode_Check(cmd
)) {
576 PyErr_SetString(PyExc_TypeError
,
577 "eval() arg 1 must be a string or code object");
582 #ifdef Py_USING_UNICODE
583 if (PyUnicode_Check(cmd
)) {
584 tmp
= PyUnicode_AsUTF8String(cmd
);
588 cf
.cf_flags
|= PyCF_SOURCE_IS_UTF8
;
591 if (PyString_AsStringAndSize(cmd
, &str
, NULL
)) {
595 while (*str
== ' ' || *str
== '\t')
598 (void)PyEval_MergeCompilerFlags(&cf
);
599 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
604 PyDoc_STRVAR(eval_doc
,
605 "eval(source[, globals[, locals]]) -> value\n\
607 Evaluate the source in the context of globals and locals.\n\
608 The source may be a string representing a Python expression\n\
609 or a code object as returned by compile().\n\
610 The globals must be a dictionary and locals can be any mappping,\n\
611 defaulting to the current globals and locals.\n\
612 If only globals is given, locals defaults to it.\n");
616 builtin_execfile(PyObject
*self
, PyObject
*args
)
619 PyObject
*globals
= Py_None
, *locals
= Py_None
;
625 if (!PyArg_ParseTuple(args
, "s|O!O:execfile",
627 &PyDict_Type
, &globals
,
630 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
631 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
634 if (globals
== Py_None
) {
635 globals
= PyEval_GetGlobals();
636 if (locals
== Py_None
)
637 locals
= PyEval_GetLocals();
639 else if (locals
== Py_None
)
641 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
642 if (PyDict_SetItemString(globals
, "__builtins__",
643 PyEval_GetBuiltins()) != 0)
648 /* Test for existence or directory. */
653 if ((d
= dirstat(filename
))!=nil
) {
655 werrstr("is a directory");
661 #elif defined(RISCOS)
662 if (object_exists(filename
)) {
668 #else /* standard Posix */
671 if (stat(filename
, &s
) == 0) {
672 if (S_ISDIR(s
.st_mode
))
673 # if defined(PYOS_OS2) && defined(PYCC_VACPP)
685 Py_BEGIN_ALLOW_THREADS
686 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
695 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
699 if (PyEval_MergeCompilerFlags(&cf
))
700 res
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, globals
,
703 res
= PyRun_FileEx(fp
, filename
, Py_file_input
, globals
,
708 PyDoc_STRVAR(execfile_doc
,
709 "execfile(filename[, globals[, locals]])\n\
711 Read and execute a Python script from a file.\n\
712 The globals and locals are dictionaries, defaulting to the current\n\
713 globals and locals. If only globals is given, locals defaults to it.");
717 builtin_getattr(PyObject
*self
, PyObject
*args
)
719 PyObject
*v
, *result
, *dflt
= NULL
;
722 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
724 #ifdef Py_USING_UNICODE
725 if (PyUnicode_Check(name
)) {
726 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
732 if (!PyString_Check(name
)) {
733 PyErr_SetString(PyExc_TypeError
,
734 "getattr(): attribute name must be string");
737 result
= PyObject_GetAttr(v
, name
);
738 if (result
== NULL
&& dflt
!= NULL
&&
739 PyErr_ExceptionMatches(PyExc_AttributeError
))
748 PyDoc_STRVAR(getattr_doc
,
749 "getattr(object, name[, default]) -> value\n\
751 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
752 When a default argument is given, it is returned when the attribute doesn't\n\
753 exist; without it, an exception is raised in that case.");
757 builtin_globals(PyObject
*self
)
761 d
= PyEval_GetGlobals();
766 PyDoc_STRVAR(globals_doc
,
767 "globals() -> dictionary\n\
769 Return the dictionary containing the current scope's global variables.");
773 builtin_hasattr(PyObject
*self
, PyObject
*args
)
778 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
780 #ifdef Py_USING_UNICODE
781 if (PyUnicode_Check(name
)) {
782 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
788 if (!PyString_Check(name
)) {
789 PyErr_SetString(PyExc_TypeError
,
790 "hasattr(): attribute name must be string");
793 v
= PyObject_GetAttr(v
, name
);
804 PyDoc_STRVAR(hasattr_doc
,
805 "hasattr(object, name) -> bool\n\
807 Return whether the object has an attribute with the given name.\n\
808 (This is done by calling getattr(object, name) and catching exceptions.)");
812 builtin_id(PyObject
*self
, PyObject
*v
)
814 return PyLong_FromVoidPtr(v
);
818 "id(object) -> integer\n\
820 Return the identity of an object. This is guaranteed to be unique among\n\
821 simultaneously existing objects. (Hint: it's the object's memory address.)");
825 builtin_map(PyObject
*self
, PyObject
*args
)
828 PyObject
*it
; /* the iterator object */
829 int saw_StopIteration
; /* bool: did the iterator end? */
832 PyObject
*func
, *result
;
833 sequence
*seqs
= NULL
, *sqp
;
837 n
= PyTuple_Size(args
);
839 PyErr_SetString(PyExc_TypeError
,
840 "map() requires at least two args");
844 func
= PyTuple_GetItem(args
, 0);
847 if (func
== Py_None
&& n
== 1) {
848 /* map(None, S) is the same as list(S). */
849 return PySequence_List(PyTuple_GetItem(args
, 1));
852 /* Get space for sequence descriptors. Must NULL out the iterator
853 * pointers so that jumping to Fail_2 later doesn't see trash.
855 if ((seqs
= PyMem_NEW(sequence
, n
)) == NULL
) {
859 for (i
= 0; i
< n
; ++i
) {
860 seqs
[i
].it
= (PyObject
*)NULL
;
861 seqs
[i
].saw_StopIteration
= 0;
864 /* Do a first pass to obtain iterators for the arguments, and set len
865 * to the largest of their lengths.
868 for (i
= 0, sqp
= seqs
; i
< n
; ++i
, ++sqp
) {
873 curseq
= PyTuple_GetItem(args
, i
+1);
874 sqp
->it
= PyObject_GetIter(curseq
);
875 if (sqp
->it
== NULL
) {
876 static char errmsg
[] =
877 "argument %d to map() must support iteration";
878 char errbuf
[sizeof(errmsg
) + 25];
879 PyOS_snprintf(errbuf
, sizeof(errbuf
), errmsg
, i
+2);
880 PyErr_SetString(PyExc_TypeError
, errbuf
);
885 curlen
= _PyObject_LengthHint(curseq
);
887 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
888 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
892 curlen
= 8; /* arbitrary */
898 /* Get space for the result list. */
899 if ((result
= (PyObject
*) PyList_New(len
)) == NULL
)
902 /* Iterate over the sequences until all have stopped. */
904 PyObject
*alist
, *item
=NULL
, *value
;
907 if (func
== Py_None
&& n
== 1)
909 else if ((alist
= PyTuple_New(n
)) == NULL
)
912 for (j
= 0, sqp
= seqs
; j
< n
; ++j
, ++sqp
) {
913 if (sqp
->saw_StopIteration
) {
918 item
= PyIter_Next(sqp
->it
);
922 if (PyErr_Occurred()) {
928 sqp
->saw_StopIteration
= 1;
932 PyTuple_SET_ITEM(alist
, j
, item
);
940 if (numactive
== 0) {
948 value
= PyEval_CallObject(func
, alist
);
954 int status
= PyList_Append(result
, value
);
959 else if (PyList_SetItem(result
, i
, value
) < 0)
963 if (i
< len
&& PyList_SetSlice(result
, i
, len
, NULL
) < 0)
974 for (i
= 0; i
< n
; ++i
)
975 Py_XDECREF(seqs
[i
].it
);
980 PyDoc_STRVAR(map_doc
,
981 "map(function, sequence[, sequence, ...]) -> list\n\
983 Return a list of the results of applying the function to the items of\n\
984 the argument sequence(s). If more than one sequence is given, the\n\
985 function is called with an argument list consisting of the corresponding\n\
986 item of each sequence, substituting None for missing values when not all\n\
987 sequences have the same length. If the function is None, return a list of\n\
988 the items of the sequence (or a list of tuples if more than one sequence).");
992 builtin_setattr(PyObject
*self
, PyObject
*args
)
998 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1000 if (PyObject_SetAttr(v
, name
, value
) != 0)
1006 PyDoc_STRVAR(setattr_doc
,
1007 "setattr(object, name, value)\n\
1009 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1014 builtin_delattr(PyObject
*self
, PyObject
*args
)
1019 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1021 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1027 PyDoc_STRVAR(delattr_doc
,
1028 "delattr(object, name)\n\
1030 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1035 builtin_hash(PyObject
*self
, PyObject
*v
)
1039 x
= PyObject_Hash(v
);
1042 return PyInt_FromLong(x
);
1045 PyDoc_STRVAR(hash_doc
,
1046 "hash(object) -> integer\n\
1048 Return a hash value for the object. Two objects with the same value have\n\
1049 the same hash value. The reverse is not necessarily true, but likely.");
1053 builtin_hex(PyObject
*self
, PyObject
*v
)
1055 PyNumberMethods
*nb
;
1058 if ((nb
= v
->ob_type
->tp_as_number
) == NULL
||
1059 nb
->nb_hex
== NULL
) {
1060 PyErr_SetString(PyExc_TypeError
,
1061 "hex() argument can't be converted to hex");
1064 res
= (*nb
->nb_hex
)(v
);
1065 if (res
&& !PyString_Check(res
)) {
1066 PyErr_Format(PyExc_TypeError
,
1067 "__hex__ returned non-string (type %.200s)",
1068 res
->ob_type
->tp_name
);
1075 PyDoc_STRVAR(hex_doc
,
1076 "hex(number) -> string\n\
1078 Return the hexadecimal representation of an integer or long integer.");
1081 static PyObject
*builtin_raw_input(PyObject
*, PyObject
*);
1084 builtin_input(PyObject
*self
, PyObject
*args
)
1089 PyObject
*globals
, *locals
;
1092 line
= builtin_raw_input(self
, args
);
1095 if (!PyArg_Parse(line
, "s;embedded '\\0' in input line", &str
))
1097 while (*str
== ' ' || *str
== '\t')
1099 globals
= PyEval_GetGlobals();
1100 locals
= PyEval_GetLocals();
1101 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
1102 if (PyDict_SetItemString(globals
, "__builtins__",
1103 PyEval_GetBuiltins()) != 0)
1107 PyEval_MergeCompilerFlags(&cf
);
1108 res
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
1113 PyDoc_STRVAR(input_doc
,
1114 "input([prompt]) -> value\n\
1116 Equivalent to eval(raw_input(prompt)).");
1120 builtin_intern(PyObject
*self
, PyObject
*args
)
1123 if (!PyArg_ParseTuple(args
, "S:intern", &s
))
1125 if (!PyString_CheckExact(s
)) {
1126 PyErr_SetString(PyExc_TypeError
,
1127 "can't intern subclass of string");
1131 PyString_InternInPlace(&s
);
1135 PyDoc_STRVAR(intern_doc
,
1136 "intern(string) -> string\n\
1138 ``Intern'' the given string. This enters the string in the (global)\n\
1139 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1140 Return the string itself or the previously interned string object with the\n\
1145 builtin_iter(PyObject
*self
, PyObject
*args
)
1147 PyObject
*v
, *w
= NULL
;
1149 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1152 return PyObject_GetIter(v
);
1153 if (!PyCallable_Check(v
)) {
1154 PyErr_SetString(PyExc_TypeError
,
1155 "iter(v, w): v must be callable");
1158 return PyCallIter_New(v
, w
);
1161 PyDoc_STRVAR(iter_doc
,
1162 "iter(collection) -> iterator\n\
1163 iter(callable, sentinel) -> iterator\n\
1165 Get an iterator from an object. In the first form, the argument must\n\
1166 supply its own iterator, or be a sequence.\n\
1167 In the second form, the callable is called until it returns the sentinel.");
1171 builtin_len(PyObject
*self
, PyObject
*v
)
1175 res
= PyObject_Size(v
);
1176 if (res
< 0 && PyErr_Occurred())
1178 return PyInt_FromSsize_t(res
);
1181 PyDoc_STRVAR(len_doc
,
1182 "len(object) -> integer\n\
1184 Return the number of items of a sequence or mapping.");
1188 builtin_locals(PyObject
*self
)
1192 d
= PyEval_GetLocals();
1197 PyDoc_STRVAR(locals_doc
,
1198 "locals() -> dictionary\n\
1200 Update and return a dictionary containing the current scope's local variables.");
1204 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1206 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1207 const char *name
= op
== Py_LT
? "min" : "max";
1209 if (PyTuple_Size(args
) > 1)
1211 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1214 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1215 keyfunc
= PyDict_GetItemString(kwds
, "key");
1216 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1217 PyErr_Format(PyExc_TypeError
,
1218 "%s() got an unexpected keyword argument", name
);
1223 it
= PyObject_GetIter(v
);
1227 maxitem
= NULL
; /* the result */
1228 maxval
= NULL
; /* the value associated with the result */
1229 while (( item
= PyIter_Next(it
) )) {
1230 /* get the value from the key function */
1231 if (keyfunc
!= NULL
) {
1232 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1236 /* no key function; the value is the item */
1242 /* maximum value and item are unset; set them */
1243 if (maxval
== NULL
) {
1247 /* maximum value and item are set; update them as necessary */
1249 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1251 goto Fail_it_item_and_val
;
1264 if (PyErr_Occurred())
1266 if (maxval
== NULL
) {
1267 PyErr_Format(PyExc_ValueError
,
1268 "%s() arg is an empty sequence", name
);
1269 assert(maxitem
== NULL
);
1276 Fail_it_item_and_val
:
1282 Py_XDECREF(maxitem
);
1288 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1290 return min_max(args
, kwds
, Py_LT
);
1293 PyDoc_STRVAR(min_doc
,
1294 "min(iterable[, key=func]) -> value\n\
1295 min(a, b, c, ...[, key=func]) -> value\n\
1297 With a single iterable argument, return its smallest item.\n\
1298 With two or more arguments, return the smallest argument.");
1302 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1304 return min_max(args
, kwds
, Py_GT
);
1307 PyDoc_STRVAR(max_doc
,
1308 "max(iterable[, key=func]) -> value\n\
1309 max(a, b, c, ...[, key=func]) -> value\n\
1311 With a single iterable argument, return its largest item.\n\
1312 With two or more arguments, return the largest argument.");
1316 builtin_oct(PyObject
*self
, PyObject
*v
)
1318 PyNumberMethods
*nb
;
1321 if (v
== NULL
|| (nb
= v
->ob_type
->tp_as_number
) == NULL
||
1322 nb
->nb_oct
== NULL
) {
1323 PyErr_SetString(PyExc_TypeError
,
1324 "oct() argument can't be converted to oct");
1327 res
= (*nb
->nb_oct
)(v
);
1328 if (res
&& !PyString_Check(res
)) {
1329 PyErr_Format(PyExc_TypeError
,
1330 "__oct__ returned non-string (type %.200s)",
1331 res
->ob_type
->tp_name
);
1338 PyDoc_STRVAR(oct_doc
,
1339 "oct(number) -> string\n\
1341 Return the octal representation of an integer or long integer.");
1345 builtin_open(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1347 return PyObject_Call((PyObject
*)&PyFile_Type
, args
, kwds
);
1350 PyDoc_STRVAR(open_doc
,
1351 "open(name[, mode[, buffering]]) -> file object\n\
1353 Open a file using the file() type, returns a file object.");
1357 builtin_ord(PyObject
*self
, PyObject
* obj
)
1362 if (PyString_Check(obj
)) {
1363 size
= PyString_GET_SIZE(obj
);
1365 ord
= (long)((unsigned char)*PyString_AS_STRING(obj
));
1366 return PyInt_FromLong(ord
);
1368 #ifdef Py_USING_UNICODE
1369 } else if (PyUnicode_Check(obj
)) {
1370 size
= PyUnicode_GET_SIZE(obj
);
1372 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1373 return PyInt_FromLong(ord
);
1377 PyErr_Format(PyExc_TypeError
,
1378 "ord() expected string of length 1, but " \
1379 "%.200s found", obj
->ob_type
->tp_name
);
1383 PyErr_Format(PyExc_TypeError
,
1384 "ord() expected a character, "
1385 "but string of length %zd found",
1390 PyDoc_STRVAR(ord_doc
,
1391 "ord(c) -> integer\n\
1393 Return the integer ordinal of a one-character string.");
1397 builtin_pow(PyObject
*self
, PyObject
*args
)
1399 PyObject
*v
, *w
, *z
= Py_None
;
1401 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1403 return PyNumber_Power(v
, w
, z
);
1406 PyDoc_STRVAR(pow_doc
,
1407 "pow(x, y[, z]) -> number\n\
1409 With two arguments, equivalent to x**y. With three arguments,\n\
1410 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1414 /* Return number of items in range (lo, hi, step), when arguments are
1415 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
1416 * & only if the true value is too large to fit in a signed long.
1417 * Arguments MUST return 1 with either PyInt_Check() or
1418 * PyLong_Check(). Return -1 when there is an error.
1421 get_len_of_range_longs(PyObject
*lo
, PyObject
*hi
, PyObject
*step
)
1423 /* -------------------------------------------------------------
1424 Algorithm is equal to that of get_len_of_range(), but it operates
1425 on PyObjects (which are assumed to be PyLong or PyInt objects).
1426 ---------------------------------------------------------------*/
1428 PyObject
*diff
= NULL
;
1429 PyObject
*one
= NULL
;
1430 PyObject
*tmp1
= NULL
, *tmp2
= NULL
, *tmp3
= NULL
;
1431 /* holds sub-expression evaluations */
1433 /* if (lo >= hi), return length of 0. */
1434 if (PyObject_Compare(lo
, hi
) >= 0)
1437 if ((one
= PyLong_FromLong(1L)) == NULL
)
1440 if ((tmp1
= PyNumber_Subtract(hi
, lo
)) == NULL
)
1443 if ((diff
= PyNumber_Subtract(tmp1
, one
)) == NULL
)
1446 if ((tmp2
= PyNumber_FloorDivide(diff
, step
)) == NULL
)
1449 if ((tmp3
= PyNumber_Add(tmp2
, one
)) == NULL
)
1452 n
= PyLong_AsLong(tmp3
);
1453 if (PyErr_Occurred()) { /* Check for Overflow */
1474 /* An extension of builtin_range() that handles the case when PyLong
1475 * arguments are given. */
1477 handle_range_longs(PyObject
*self
, PyObject
*args
)
1480 PyObject
*ihigh
= NULL
;
1481 PyObject
*istep
= NULL
;
1483 PyObject
*curnum
= NULL
;
1489 PyObject
*zero
= PyLong_FromLong(0);
1494 if (!PyArg_UnpackTuple(args
, "range", 1, 3, &ilow
, &ihigh
, &istep
)) {
1499 /* Figure out which way we were called, supply defaults, and be
1500 * sure to incref everything so that the decrefs at the end
1503 assert(ilow
!= NULL
);
1504 if (ihigh
== NULL
) {
1505 /* only 1 arg -- it's the upper limit */
1509 assert(ihigh
!= NULL
);
1512 /* ihigh correct now; do ilow */
1517 /* ilow and ihigh correct now; do istep */
1518 if (istep
== NULL
) {
1519 istep
= PyLong_FromLong(1L);
1527 if (!PyInt_Check(ilow
) && !PyLong_Check(ilow
)) {
1528 PyErr_Format(PyExc_TypeError
,
1529 "range() integer start argument expected, got %s.",
1530 ilow
->ob_type
->tp_name
);
1534 if (!PyInt_Check(ihigh
) && !PyLong_Check(ihigh
)) {
1535 PyErr_Format(PyExc_TypeError
,
1536 "range() integer end argument expected, got %s.",
1537 ihigh
->ob_type
->tp_name
);
1541 if (!PyInt_Check(istep
) && !PyLong_Check(istep
)) {
1542 PyErr_Format(PyExc_TypeError
,
1543 "range() integer step argument expected, got %s.",
1544 istep
->ob_type
->tp_name
);
1548 if (PyObject_Cmp(istep
, zero
, &cmp_result
) == -1)
1550 if (cmp_result
== 0) {
1551 PyErr_SetString(PyExc_ValueError
,
1552 "range() step argument must not be zero");
1557 bign
= get_len_of_range_longs(ilow
, ihigh
, istep
);
1559 PyObject
*neg_istep
= PyNumber_Negative(istep
);
1560 if (neg_istep
== NULL
)
1562 bign
= get_len_of_range_longs(ihigh
, ilow
, neg_istep
);
1563 Py_DECREF(neg_istep
);
1567 if (bign
< 0 || (long)n
!= bign
) {
1568 PyErr_SetString(PyExc_OverflowError
,
1569 "range() result has too many items");
1580 for (i
= 0; i
< n
; i
++) {
1581 PyObject
*w
= PyNumber_Long(curnum
);
1586 PyList_SET_ITEM(v
, i
, w
);
1588 tmp_num
= PyNumber_Add(curnum
, istep
);
1589 if (tmp_num
== NULL
)
1612 /* Return number of items in range/xrange (lo, hi, step). step > 0
1613 * required. Return a value < 0 if & only if the true value is too
1614 * large to fit in a signed long.
1617 get_len_of_range(long lo
, long hi
, long step
)
1619 /* -------------------------------------------------------------
1620 If lo >= hi, the range is empty.
1621 Else if n values are in the range, the last one is
1622 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1623 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1624 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1625 the RHS is non-negative and so truncation is the same as the
1626 floor. Letting M be the largest positive long, the worst case
1627 for the RHS numerator is hi=M, lo=-M-1, and then
1628 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1629 precision to compute the RHS exactly.
1630 ---------------------------------------------------------------*/
1633 unsigned long uhi
= (unsigned long)hi
;
1634 unsigned long ulo
= (unsigned long)lo
;
1635 unsigned long diff
= uhi
- ulo
- 1;
1636 n
= (long)(diff
/ (unsigned long)step
+ 1);
1642 builtin_range(PyObject
*self
, PyObject
*args
)
1644 long ilow
= 0, ihigh
= 0, istep
= 1;
1650 if (PyTuple_Size(args
) <= 1) {
1651 if (!PyArg_ParseTuple(args
,
1652 "l;range() requires 1-3 int arguments",
1655 return handle_range_longs(self
, args
);
1659 if (!PyArg_ParseTuple(args
,
1660 "ll|l;range() requires 1-3 int arguments",
1661 &ilow
, &ihigh
, &istep
)) {
1663 return handle_range_longs(self
, args
);
1667 PyErr_SetString(PyExc_ValueError
,
1668 "range() step argument must not be zero");
1672 bign
= get_len_of_range(ilow
, ihigh
, istep
);
1674 bign
= get_len_of_range(ihigh
, ilow
, -istep
);
1676 if (bign
< 0 || (long)n
!= bign
) {
1677 PyErr_SetString(PyExc_OverflowError
,
1678 "range() result has too many items");
1684 for (i
= 0; i
< n
; i
++) {
1685 PyObject
*w
= PyInt_FromLong(ilow
);
1690 PyList_SET_ITEM(v
, i
, w
);
1696 PyDoc_STRVAR(range_doc
,
1697 "range([start,] stop[, step]) -> list of integers\n\
1699 Return a list containing an arithmetic progression of integers.\n\
1700 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1701 When step is given, it specifies the increment (or decrement).\n\
1702 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1703 These are exactly the valid indices for a list of 4 elements.");
1707 builtin_raw_input(PyObject
*self
, PyObject
*args
)
1710 PyObject
*fin
= PySys_GetObject("stdin");
1711 PyObject
*fout
= PySys_GetObject("stdout");
1713 if (!PyArg_UnpackTuple(args
, "[raw_]input", 0, 1, &v
))
1717 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdin");
1721 PyErr_SetString(PyExc_RuntimeError
, "[raw_]input: lost sys.stdout");
1724 if (PyFile_SoftSpace(fout
, 0)) {
1725 if (PyFile_WriteString(" ", fout
) != 0)
1728 if (PyFile_Check(fin
) && PyFile_Check(fout
)
1729 && isatty(fileno(PyFile_AsFile(fin
)))
1730 && isatty(fileno(PyFile_AsFile(fout
)))) {
1736 po
= PyObject_Str(v
);
1739 prompt
= PyString_AsString(po
);
1747 s
= PyOS_Readline(PyFile_AsFile(fin
), PyFile_AsFile(fout
),
1751 if (!PyErr_Occurred())
1752 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1756 PyErr_SetNone(PyExc_EOFError
);
1759 else { /* strip trailing '\n' */
1760 size_t len
= strlen(s
);
1761 if (len
> PY_SSIZE_T_MAX
) {
1762 PyErr_SetString(PyExc_OverflowError
,
1763 "[raw_]input: input too long");
1767 result
= PyString_FromStringAndSize(s
, len
-1);
1774 if (PyFile_WriteObject(v
, fout
, Py_PRINT_RAW
) != 0)
1777 return PyFile_GetLine(fin
, -1);
1780 PyDoc_STRVAR(raw_input_doc
,
1781 "raw_input([prompt]) -> string\n\
1783 Read a string from standard input. The trailing newline is stripped.\n\
1784 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1785 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1786 is printed without a trailing newline before reading.");
1790 builtin_reduce(PyObject
*self
, PyObject
*args
)
1792 PyObject
*seq
, *func
, *result
= NULL
, *it
;
1794 if (!PyArg_UnpackTuple(args
, "reduce", 2, 3, &func
, &seq
, &result
))
1799 it
= PyObject_GetIter(seq
);
1801 PyErr_SetString(PyExc_TypeError
,
1802 "reduce() arg 2 must support iteration");
1807 if ((args
= PyTuple_New(2)) == NULL
)
1813 if (args
->ob_refcnt
> 1) {
1815 if ((args
= PyTuple_New(2)) == NULL
)
1819 op2
= PyIter_Next(it
);
1821 if (PyErr_Occurred())
1829 PyTuple_SetItem(args
, 0, result
);
1830 PyTuple_SetItem(args
, 1, op2
);
1831 if ((result
= PyEval_CallObject(func
, args
)) == NULL
)
1839 PyErr_SetString(PyExc_TypeError
,
1840 "reduce() of empty sequence with no initial value");
1852 PyDoc_STRVAR(reduce_doc
,
1853 "reduce(function, sequence[, initial]) -> value\n\
1855 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1856 from left to right, so as to reduce the sequence to a single value.\n\
1857 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1858 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1859 of the sequence in the calculation, and serves as a default when the\n\
1860 sequence is empty.");
1864 builtin_reload(PyObject
*self
, PyObject
*v
)
1866 return PyImport_ReloadModule(v
);
1869 PyDoc_STRVAR(reload_doc
,
1870 "reload(module) -> module\n\
1872 Reload the module. The module must have been successfully imported before.");
1876 builtin_repr(PyObject
*self
, PyObject
*v
)
1878 return PyObject_Repr(v
);
1881 PyDoc_STRVAR(repr_doc
,
1882 "repr(object) -> string\n\
1884 Return the canonical string representation of the object.\n\
1885 For most object types, eval(repr(object)) == object.");
1889 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1895 static char *kwlist
[] = {"number", "ndigits", 0};
1897 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "d|i:round",
1898 kwlist
, &number
, &ndigits
))
1909 number
= floor(number
+ 0.5);
1911 number
= ceil(number
- 0.5);
1916 return PyFloat_FromDouble(number
);
1919 PyDoc_STRVAR(round_doc
,
1920 "round(number[, ndigits]) -> floating point number\n\
1922 Round a number to a given precision in decimal digits (default 0 digits).\n\
1923 This always returns a floating point number. Precision may be negative.");
1926 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1928 PyObject
*newlist
, *v
, *seq
, *compare
=NULL
, *keyfunc
=NULL
, *newargs
;
1930 static char *kwlist
[] = {"iterable", "cmp", "key", "reverse", 0};
1933 /* args 1-4 should match listsort in Objects/listobject.c */
1934 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|OOi:sorted",
1935 kwlist
, &seq
, &compare
, &keyfunc
, &reverse
))
1938 newlist
= PySequence_List(seq
);
1939 if (newlist
== NULL
)
1942 callable
= PyObject_GetAttrString(newlist
, "sort");
1943 if (callable
== NULL
) {
1948 newargs
= PyTuple_GetSlice(args
, 1, 4);
1949 if (newargs
== NULL
) {
1951 Py_DECREF(callable
);
1955 v
= PyObject_Call(callable
, newargs
, kwds
);
1957 Py_DECREF(callable
);
1966 PyDoc_STRVAR(sorted_doc
,
1967 "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
1970 builtin_vars(PyObject
*self
, PyObject
*args
)
1975 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
1978 d
= PyEval_GetLocals();
1980 if (!PyErr_Occurred())
1981 PyErr_SetString(PyExc_SystemError
,
1982 "vars(): no locals!?");
1988 d
= PyObject_GetAttrString(v
, "__dict__");
1990 PyErr_SetString(PyExc_TypeError
,
1991 "vars() argument must have __dict__ attribute");
1998 PyDoc_STRVAR(vars_doc
,
1999 "vars([object]) -> dictionary\n\
2001 Without arguments, equivalent to locals().\n\
2002 With an argument, equivalent to object.__dict__.");
2006 builtin_sum(PyObject
*self
, PyObject
*args
)
2009 PyObject
*result
= NULL
;
2010 PyObject
*temp
, *item
, *iter
;
2012 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
2015 iter
= PyObject_GetIter(seq
);
2019 if (result
== NULL
) {
2020 result
= PyInt_FromLong(0);
2021 if (result
== NULL
) {
2026 /* reject string values for 'start' parameter */
2027 if (PyObject_TypeCheck(result
, &PyBaseString_Type
)) {
2028 PyErr_SetString(PyExc_TypeError
,
2029 "sum() can't sum strings [use ''.join(seq) instead]");
2037 item
= PyIter_Next(iter
);
2039 /* error, or end-of-sequence */
2040 if (PyErr_Occurred()) {
2046 temp
= PyNumber_Add(result
, item
);
2057 PyDoc_STRVAR(sum_doc
,
2058 "sum(sequence, start=0) -> value\n\
2060 Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
2061 of parameter 'start'. When the sequence is empty, returns start.");
2065 builtin_isinstance(PyObject
*self
, PyObject
*args
)
2071 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2074 retval
= PyObject_IsInstance(inst
, cls
);
2077 return PyBool_FromLong(retval
);
2080 PyDoc_STRVAR(isinstance_doc
,
2081 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2083 Return whether an object is an instance of a class or of a subclass thereof.\n\
2084 With a type as second argument, return whether that is the object's type.\n\
2085 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2086 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2090 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2096 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2099 retval
= PyObject_IsSubclass(derived
, cls
);
2102 return PyBool_FromLong(retval
);
2105 PyDoc_STRVAR(issubclass_doc
,
2106 "issubclass(C, B) -> bool\n\
2108 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2109 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2110 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2114 builtin_zip(PyObject
*self
, PyObject
*args
)
2117 const Py_ssize_t itemsize
= PySequence_Length(args
);
2119 PyObject
*itlist
; /* tuple of iterators */
2120 Py_ssize_t len
; /* guess at result length */
2123 return PyList_New(0);
2125 /* args must be a tuple */
2126 assert(PyTuple_Check(args
));
2128 /* Guess at result length: the shortest of the input lengths.
2129 If some argument refuses to say, we refuse to guess too, lest
2130 an argument like xrange(sys.maxint) lead us astray.*/
2131 len
= -1; /* unknown */
2132 for (i
= 0; i
< itemsize
; ++i
) {
2133 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2134 Py_ssize_t thislen
= _PyObject_LengthHint(item
);
2136 if (!PyErr_ExceptionMatches(PyExc_TypeError
) &&
2137 !PyErr_ExceptionMatches(PyExc_AttributeError
)) {
2144 else if (len
< 0 || thislen
< len
)
2148 /* allocate result list */
2150 len
= 10; /* arbitrary */
2151 if ((ret
= PyList_New(len
)) == NULL
)
2154 /* obtain iterators */
2155 itlist
= PyTuple_New(itemsize
);
2158 for (i
= 0; i
< itemsize
; ++i
) {
2159 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2160 PyObject
*it
= PyObject_GetIter(item
);
2162 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2163 PyErr_Format(PyExc_TypeError
,
2164 "zip argument #%zd must support iteration",
2166 goto Fail_ret_itlist
;
2168 PyTuple_SET_ITEM(itlist
, i
, it
);
2171 /* build result into ret list */
2172 for (i
= 0; ; ++i
) {
2174 PyObject
*next
= PyTuple_New(itemsize
);
2176 goto Fail_ret_itlist
;
2178 for (j
= 0; j
< itemsize
; j
++) {
2179 PyObject
*it
= PyTuple_GET_ITEM(itlist
, j
);
2180 PyObject
*item
= PyIter_Next(it
);
2182 if (PyErr_Occurred()) {
2190 PyTuple_SET_ITEM(next
, j
, item
);
2194 PyList_SET_ITEM(ret
, i
, next
);
2196 int status
= PyList_Append(ret
, next
);
2200 goto Fail_ret_itlist
;
2205 if (ret
!= NULL
&& i
< len
) {
2206 /* The list is too big. */
2207 if (PyList_SetSlice(ret
, i
, len
, NULL
) < 0)
2220 PyDoc_STRVAR(zip_doc
,
2221 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2223 Return a list of tuples, where each tuple contains the i-th element\n\
2224 from each of the argument sequences. The returned list is truncated\n\
2225 in length to the length of the shortest argument sequence.");
2228 static PyMethodDef builtin_methods
[] = {
2229 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2230 {"abs", builtin_abs
, METH_O
, abs_doc
},
2231 {"all", builtin_all
, METH_O
, all_doc
},
2232 {"any", builtin_any
, METH_O
, any_doc
},
2233 {"apply", builtin_apply
, METH_VARARGS
, apply_doc
},
2234 {"callable", builtin_callable
, METH_O
, callable_doc
},
2235 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2236 {"cmp", builtin_cmp
, METH_VARARGS
, cmp_doc
},
2237 {"coerce", builtin_coerce
, METH_VARARGS
, coerce_doc
},
2238 {"compile", builtin_compile
, METH_VARARGS
, compile_doc
},
2239 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2240 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2241 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2242 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2243 {"execfile", builtin_execfile
, METH_VARARGS
, execfile_doc
},
2244 {"filter", builtin_filter
, METH_VARARGS
, filter_doc
},
2245 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2246 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2247 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2248 {"hash", builtin_hash
, METH_O
, hash_doc
},
2249 {"hex", builtin_hex
, METH_O
, hex_doc
},
2250 {"id", builtin_id
, METH_O
, id_doc
},
2251 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2252 {"intern", builtin_intern
, METH_VARARGS
, intern_doc
},
2253 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2254 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2255 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2256 {"len", builtin_len
, METH_O
, len_doc
},
2257 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2258 {"map", builtin_map
, METH_VARARGS
, map_doc
},
2259 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2260 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2261 {"oct", builtin_oct
, METH_O
, oct_doc
},
2262 {"open", (PyCFunction
)builtin_open
, METH_VARARGS
| METH_KEYWORDS
, open_doc
},
2263 {"ord", builtin_ord
, METH_O
, ord_doc
},
2264 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2265 {"range", builtin_range
, METH_VARARGS
, range_doc
},
2266 {"raw_input", builtin_raw_input
, METH_VARARGS
, raw_input_doc
},
2267 {"reduce", builtin_reduce
, METH_VARARGS
, reduce_doc
},
2268 {"reload", builtin_reload
, METH_O
, reload_doc
},
2269 {"repr", builtin_repr
, METH_O
, repr_doc
},
2270 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2271 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2272 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2273 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2274 #ifdef Py_USING_UNICODE
2275 {"unichr", builtin_unichr
, METH_VARARGS
, unichr_doc
},
2277 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2278 {"zip", builtin_zip
, METH_VARARGS
, zip_doc
},
2282 PyDoc_STRVAR(builtin_doc
,
2283 "Built-in functions, exceptions, and other objects.\n\
2285 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2288 _PyBuiltin_Init(void)
2290 PyObject
*mod
, *dict
, *debug
;
2291 mod
= Py_InitModule4("__builtin__", builtin_methods
,
2292 builtin_doc
, (PyObject
*)NULL
,
2293 PYTHON_API_VERSION
);
2296 dict
= PyModule_GetDict(mod
);
2298 #ifdef Py_TRACE_REFS
2299 /* __builtin__ exposes a number of statically allocated objects
2300 * that, before this code was added in 2.3, never showed up in
2301 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2302 * result, programs leaking references to None and False (etc)
2303 * couldn't be diagnosed by examining sys.getobjects(0).
2305 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2307 #define ADD_TO_ALL(OBJECT) (void)0
2310 #define SETBUILTIN(NAME, OBJECT) \
2311 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2315 SETBUILTIN("None", Py_None
);
2316 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2317 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2318 SETBUILTIN("False", Py_False
);
2319 SETBUILTIN("True", Py_True
);
2320 SETBUILTIN("basestring", &PyBaseString_Type
);
2321 SETBUILTIN("bool", &PyBool_Type
);
2322 SETBUILTIN("buffer", &PyBuffer_Type
);
2323 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2324 #ifndef WITHOUT_COMPLEX
2325 SETBUILTIN("complex", &PyComplex_Type
);
2327 SETBUILTIN("dict", &PyDict_Type
);
2328 SETBUILTIN("enumerate", &PyEnum_Type
);
2329 SETBUILTIN("file", &PyFile_Type
);
2330 SETBUILTIN("float", &PyFloat_Type
);
2331 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2332 SETBUILTIN("property", &PyProperty_Type
);
2333 SETBUILTIN("int", &PyInt_Type
);
2334 SETBUILTIN("list", &PyList_Type
);
2335 SETBUILTIN("long", &PyLong_Type
);
2336 SETBUILTIN("object", &PyBaseObject_Type
);
2337 SETBUILTIN("reversed", &PyReversed_Type
);
2338 SETBUILTIN("set", &PySet_Type
);
2339 SETBUILTIN("slice", &PySlice_Type
);
2340 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2341 SETBUILTIN("str", &PyString_Type
);
2342 SETBUILTIN("super", &PySuper_Type
);
2343 SETBUILTIN("tuple", &PyTuple_Type
);
2344 SETBUILTIN("type", &PyType_Type
);
2345 SETBUILTIN("xrange", &PyRange_Type
);
2346 #ifdef Py_USING_UNICODE
2347 SETBUILTIN("unicode", &PyUnicode_Type
);
2349 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2350 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {
2361 /* Helper for filter(): filter a tuple through a function */
2364 filtertuple(PyObject
*func
, PyObject
*tuple
)
2368 Py_ssize_t len
= PyTuple_Size(tuple
);
2371 if (PyTuple_CheckExact(tuple
))
2374 tuple
= PyTuple_New(0);
2378 if ((result
= PyTuple_New(len
)) == NULL
)
2381 for (i
= j
= 0; i
< len
; ++i
) {
2382 PyObject
*item
, *good
;
2385 if (tuple
->ob_type
->tp_as_sequence
&&
2386 tuple
->ob_type
->tp_as_sequence
->sq_item
) {
2387 item
= tuple
->ob_type
->tp_as_sequence
->sq_item(tuple
, i
);
2391 PyErr_SetString(PyExc_TypeError
, "filter(): unsubscriptable tuple");
2394 if (func
== Py_None
) {
2399 PyObject
*arg
= PyTuple_Pack(1, item
);
2404 good
= PyEval_CallObject(func
, arg
);
2411 ok
= PyObject_IsTrue(good
);
2414 if (PyTuple_SetItem(result
, j
++, item
) < 0)
2421 if (_PyTuple_Resize(&result
, j
) < 0)
2432 /* Helper for filter(): filter a string through a function */
2435 filterstring(PyObject
*func
, PyObject
*strobj
)
2439 Py_ssize_t len
= PyString_Size(strobj
);
2440 Py_ssize_t outlen
= len
;
2442 if (func
== Py_None
) {
2443 /* If it's a real string we can return the original,
2444 * as no character is ever false and __getitem__
2445 * does return this character. If it's a subclass
2446 * we must go through the __getitem__ loop */
2447 if (PyString_CheckExact(strobj
)) {
2452 if ((result
= PyString_FromStringAndSize(NULL
, len
)) == NULL
)
2455 for (i
= j
= 0; i
< len
; ++i
) {
2459 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2462 if (func
==Py_None
) {
2465 PyObject
*arg
, *good
;
2466 arg
= PyTuple_Pack(1, item
);
2471 good
= PyEval_CallObject(func
, arg
);
2477 ok
= PyObject_IsTrue(good
);
2482 if (!PyString_Check(item
)) {
2483 PyErr_SetString(PyExc_TypeError
, "can't filter str to str:"
2484 " __getitem__ returned different type");
2488 reslen
= PyString_GET_SIZE(item
);
2490 PyString_AS_STRING(result
)[j
++] =
2491 PyString_AS_STRING(item
)[0];
2493 /* do we need more space? */
2494 Py_ssize_t need
= j
+ reslen
+ len
-i
-1;
2495 if (need
> outlen
) {
2496 /* overallocate, to avoid reallocations */
2499 if (_PyString_Resize(&result
, need
)) {
2506 PyString_AS_STRING(result
) + j
,
2507 PyString_AS_STRING(item
),
2517 _PyString_Resize(&result
, j
);
2526 #ifdef Py_USING_UNICODE
2527 /* Helper for filter(): filter a Unicode object through a function */
2530 filterunicode(PyObject
*func
, PyObject
*strobj
)
2533 register Py_ssize_t i
, j
;
2534 Py_ssize_t len
= PyUnicode_GetSize(strobj
);
2535 Py_ssize_t outlen
= len
;
2537 if (func
== Py_None
) {
2538 /* If it's a real string we can return the original,
2539 * as no character is ever false and __getitem__
2540 * does return this character. If it's a subclass
2541 * we must go through the __getitem__ loop */
2542 if (PyUnicode_CheckExact(strobj
)) {
2547 if ((result
= PyUnicode_FromUnicode(NULL
, len
)) == NULL
)
2550 for (i
= j
= 0; i
< len
; ++i
) {
2551 PyObject
*item
, *arg
, *good
;
2554 item
= (*strobj
->ob_type
->tp_as_sequence
->sq_item
)(strobj
, i
);
2557 if (func
== Py_None
) {
2560 arg
= PyTuple_Pack(1, item
);
2565 good
= PyEval_CallObject(func
, arg
);
2571 ok
= PyObject_IsTrue(good
);
2576 if (!PyUnicode_Check(item
)) {
2577 PyErr_SetString(PyExc_TypeError
,
2578 "can't filter unicode to unicode:"
2579 " __getitem__ returned different type");
2583 reslen
= PyUnicode_GET_SIZE(item
);
2585 PyUnicode_AS_UNICODE(result
)[j
++] =
2586 PyUnicode_AS_UNICODE(item
)[0];
2588 /* do we need more space? */
2589 Py_ssize_t need
= j
+ reslen
+ len
- i
- 1;
2590 if (need
> outlen
) {
2592 to avoid reallocations */
2593 if (need
< 2 * outlen
)
2595 if (PyUnicode_Resize(
2596 &result
, need
) < 0) {
2602 memcpy(PyUnicode_AS_UNICODE(result
) + j
,
2603 PyUnicode_AS_UNICODE(item
),
2604 reslen
*sizeof(Py_UNICODE
));
2612 PyUnicode_Resize(&result
, j
);