1 /* Built-in functions */
4 #include "Python-ast.h"
12 /* The default encoding used by the platform file system APIs
13 Can remain NULL for all platforms that don't have such a concept
15 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
16 values for Py_FileSystemDefaultEncoding!
18 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
19 const char *Py_FileSystemDefaultEncoding
= "mbcs";
20 int Py_HasFileSystemDefaultEncoding
= 1;
21 #elif defined(__APPLE__)
22 const char *Py_FileSystemDefaultEncoding
= "utf-8";
23 int Py_HasFileSystemDefaultEncoding
= 1;
25 const char *Py_FileSystemDefaultEncoding
= NULL
; /* use default */
26 int Py_HasFileSystemDefaultEncoding
= 0;
30 _Py_SetFileSystemEncoding(PyObject
*s
)
32 PyObject
*defenc
, *codec
;
33 if (!PyUnicode_Check(s
)) {
34 PyErr_BadInternalCall();
37 defenc
= _PyUnicode_AsDefaultEncodedString(s
, NULL
);
40 codec
= _PyCodec_Lookup(PyBytes_AsString(defenc
));
44 if (!Py_HasFileSystemDefaultEncoding
&& Py_FileSystemDefaultEncoding
)
45 /* A file system encoding was set at run-time */
46 free((char*)Py_FileSystemDefaultEncoding
);
47 Py_FileSystemDefaultEncoding
= strdup(PyBytes_AsString(defenc
));
48 Py_HasFileSystemDefaultEncoding
= 0;
53 builtin___build_class__(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
55 PyObject
*func
, *name
, *bases
, *mkw
, *meta
, *prep
, *ns
, *cell
;
57 Py_ssize_t nargs
, nbases
;
60 if (!PyTuple_Check(args
)) {
61 PyErr_SetString(PyExc_TypeError
,
62 "__build_class__: args is not a tuple");
65 nargs
= PyTuple_GET_SIZE(args
);
67 PyErr_SetString(PyExc_TypeError
,
68 "__build_class__: not enough arguments");
71 func
= PyTuple_GET_ITEM(args
, 0); /* Better be callable */
72 name
= PyTuple_GET_ITEM(args
, 1);
73 if (!PyUnicode_Check(name
)) {
74 PyErr_SetString(PyExc_TypeError
,
75 "__build_class__: name is not a string");
78 bases
= PyTuple_GetSlice(args
, 2, nargs
);
88 mkw
= PyDict_Copy(kwds
); /* Don't modify kwds passed in! */
93 meta
= PyDict_GetItemString(mkw
, "metaclass");
96 if (PyDict_DelItemString(mkw
, "metaclass") < 0) {
105 if (PyTuple_GET_SIZE(bases
) == 0)
106 meta
= (PyObject
*) (&PyType_Type
);
108 PyObject
*base0
= PyTuple_GET_ITEM(bases
, 0);
109 meta
= (PyObject
*) (base0
->ob_type
);
113 prep
= PyObject_GetAttrString(meta
, "__prepare__");
115 if (PyErr_ExceptionMatches(PyExc_AttributeError
)) {
127 PyObject
*pargs
= PyTuple_Pack(2, name
, bases
);
135 ns
= PyEval_CallObjectWithKeywords(prep
, pargs
, mkw
);
145 cell
= PyObject_CallFunctionObjArgs(func
, ns
, NULL
);
148 margs
= PyTuple_Pack(3, name
, bases
, ns
);
150 cls
= PyEval_CallObjectWithKeywords(meta
, margs
, mkw
);
153 if (cls
!= NULL
&& PyCell_Check(cell
)) {
155 PyCell_SET(cell
, cls
);
166 PyDoc_STRVAR(build_class_doc
,
167 "__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
169 Internal helper function used by the class statement.");
172 builtin___import__(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
174 static char *kwlist
[] = {"name", "globals", "locals", "fromlist",
177 PyObject
*globals
= NULL
;
178 PyObject
*locals
= NULL
;
179 PyObject
*fromlist
= NULL
;
182 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "s|OOOi:__import__",
183 kwlist
, &name
, &globals
, &locals
, &fromlist
, &level
))
185 return PyImport_ImportModuleLevel(name
, globals
, locals
,
189 PyDoc_STRVAR(import_doc
,
190 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
192 Import a module. The globals are only used to determine the context;\n\
193 they are not modified. The locals are currently unused. The fromlist\n\
194 should be a list of names to emulate ``from name import ...'', or an\n\
195 empty list to emulate ``import name''.\n\
196 When importing a module from a package, note that __import__('A.B', ...)\n\
197 returns package A when fromlist is empty, but its submodule B when\n\
198 fromlist is not empty. Level is used to determine whether to perform \n\
199 absolute or relative imports. -1 is the original strategy of attempting\n\
200 both absolute and relative imports, 0 is absolute, a positive number\n\
201 is the number of parent directories to search relative to the current module.");
205 builtin_abs(PyObject
*self
, PyObject
*v
)
207 return PyNumber_Absolute(v
);
210 PyDoc_STRVAR(abs_doc
,
211 "abs(number) -> number\n\
213 Return the absolute value of the argument.");
216 builtin_all(PyObject
*self
, PyObject
*v
)
219 PyObject
*(*iternext
)(PyObject
*);
222 it
= PyObject_GetIter(v
);
225 iternext
= *Py_TYPE(it
)->tp_iternext
;
231 cmp
= PyObject_IsTrue(item
);
243 if (PyErr_Occurred()) {
244 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
252 PyDoc_STRVAR(all_doc
,
253 "all(iterable) -> bool\n\
255 Return True if bool(x) is True for all values x in the iterable.");
258 builtin_any(PyObject
*self
, PyObject
*v
)
261 PyObject
*(*iternext
)(PyObject
*);
264 it
= PyObject_GetIter(v
);
267 iternext
= *Py_TYPE(it
)->tp_iternext
;
273 cmp
= PyObject_IsTrue(item
);
285 if (PyErr_Occurred()) {
286 if (PyErr_ExceptionMatches(PyExc_StopIteration
))
294 PyDoc_STRVAR(any_doc
,
295 "any(iterable) -> bool\n\
297 Return True if bool(x) is True for any x in the iterable.");
300 builtin_ascii(PyObject
*self
, PyObject
*v
)
302 return PyObject_ASCII(v
);
305 PyDoc_STRVAR(ascii_doc
,
306 "ascii(object) -> string\n\
308 As repr(), return a string containing a printable representation of an\n\
309 object, but escape the non-ASCII characters in the string returned by\n\
310 repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
311 to that returned by repr() in Python 2.");
315 builtin_bin(PyObject
*self
, PyObject
*v
)
317 return PyNumber_ToBase(v
, 2);
320 PyDoc_STRVAR(bin_doc
,
321 "bin(number) -> string\n\
323 Return the binary representation of an integer or long integer.");
333 filter_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
335 PyObject
*func
, *seq
;
339 if (type
== &PyFilter_Type
&& !_PyArg_NoKeywords("filter()", kwds
))
342 if (!PyArg_UnpackTuple(args
, "filter", 2, 2, &func
, &seq
))
346 it
= PyObject_GetIter(seq
);
350 /* create filterobject structure */
351 lz
= (filterobject
*)type
->tp_alloc(type
, 0);
360 return (PyObject
*)lz
;
364 filter_dealloc(filterobject
*lz
)
366 PyObject_GC_UnTrack(lz
);
367 Py_XDECREF(lz
->func
);
369 Py_TYPE(lz
)->tp_free(lz
);
373 filter_traverse(filterobject
*lz
, visitproc visit
, void *arg
)
381 filter_next(filterobject
*lz
)
384 PyObject
*it
= lz
->it
;
386 PyObject
*(*iternext
)(PyObject
*);
388 iternext
= *Py_TYPE(it
)->tp_iternext
;
394 if (lz
->func
== Py_None
|| lz
->func
== (PyObject
*)&PyBool_Type
) {
395 ok
= PyObject_IsTrue(item
);
398 good
= PyObject_CallFunctionObjArgs(lz
->func
,
404 ok
= PyObject_IsTrue(good
);
413 PyDoc_STRVAR(filter_doc
,
414 "filter(function or None, iterable) --> filter object\n\
416 Return an iterator yielding those items of iterable for which function(item)\n\
417 is true. If function is None, return the items that are true.");
419 PyTypeObject PyFilter_Type
= {
420 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
421 "filter", /* tp_name */
422 sizeof(filterobject
), /* tp_basicsize */
425 (destructor
)filter_dealloc
, /* tp_dealloc */
431 0, /* tp_as_number */
432 0, /* tp_as_sequence */
433 0, /* tp_as_mapping */
437 PyObject_GenericGetAttr
, /* tp_getattro */
439 0, /* tp_as_buffer */
440 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
441 Py_TPFLAGS_BASETYPE
, /* tp_flags */
442 filter_doc
, /* tp_doc */
443 (traverseproc
)filter_traverse
, /* tp_traverse */
445 0, /* tp_richcompare */
446 0, /* tp_weaklistoffset */
447 PyObject_SelfIter
, /* tp_iter */
448 (iternextfunc
)filter_next
, /* tp_iternext */
454 0, /* tp_descr_get */
455 0, /* tp_descr_set */
456 0, /* tp_dictoffset */
458 PyType_GenericAlloc
, /* tp_alloc */
459 filter_new
, /* tp_new */
460 PyObject_GC_Del
, /* tp_free */
465 builtin_format(PyObject
*self
, PyObject
*args
)
468 PyObject
*format_spec
= NULL
;
470 if (!PyArg_ParseTuple(args
, "O|U:format", &value
, &format_spec
))
473 return PyObject_Format(value
, format_spec
);
476 PyDoc_STRVAR(format_doc
,
477 "format(value[, format_spec]) -> string\n\
479 Returns value.__format__(format_spec)\n\
480 format_spec defaults to \"\"");
483 builtin_chr(PyObject
*self
, PyObject
*args
)
487 if (!PyArg_ParseTuple(args
, "i:chr", &x
))
490 return PyUnicode_FromOrdinal(x
);
493 PyDoc_VAR(chr_doc
) = PyDoc_STR(
494 "chr(i) -> Unicode character\n\
496 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
498 #ifndef Py_UNICODE_WIDE
500 "\nIf 0x10000 <= i, a surrogate pair is returned."
507 source_as_string(PyObject
*cmd
, char *funcname
, char *what
, PyCompilerFlags
*cf
)
512 if (PyUnicode_Check(cmd
)) {
513 cf
->cf_flags
|= PyCF_IGNORE_COOKIE
;
514 cmd
= _PyUnicode_AsDefaultEncodedString(cmd
, NULL
);
518 else if (!PyObject_CheckReadBuffer(cmd
)) {
519 PyErr_Format(PyExc_TypeError
,
520 "%s() arg 1 must be a %s object",
524 if (PyObject_AsReadBuffer(cmd
, (const void **)&str
, &size
) < 0) {
527 if (strlen(str
) != size
) {
528 PyErr_SetString(PyExc_TypeError
,
529 "source code string cannot contain null bytes");
536 builtin_compile(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
542 int dont_inherit
= 0;
543 int supplied_flags
= 0;
547 static char *kwlist
[] = {"source", "filename", "mode", "flags",
548 "dont_inherit", NULL
};
549 int start
[] = {Py_file_input
, Py_eval_input
, Py_single_input
};
551 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "Oss|ii:compile",
552 kwlist
, &cmd
, &filename
, &startstr
,
553 &supplied_flags
, &dont_inherit
))
556 cf
.cf_flags
= supplied_flags
| PyCF_SOURCE_IS_UTF8
;
559 ~(PyCF_MASK
| PyCF_MASK_OBSOLETE
| PyCF_DONT_IMPLY_DEDENT
| PyCF_ONLY_AST
))
561 PyErr_SetString(PyExc_ValueError
,
562 "compile(): unrecognised flags");
565 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
568 PyEval_MergeCompilerFlags(&cf
);
571 if (strcmp(startstr
, "exec") == 0)
573 else if (strcmp(startstr
, "eval") == 0)
575 else if (strcmp(startstr
, "single") == 0)
578 PyErr_SetString(PyExc_ValueError
,
579 "compile() arg 3 must be 'exec', 'eval' or 'single'");
583 is_ast
= PyAST_Check(cmd
);
588 if (supplied_flags
& PyCF_ONLY_AST
) {
596 arena
= PyArena_New();
597 mod
= PyAST_obj2mod(cmd
, arena
, mode
);
602 result
= (PyObject
*)PyAST_Compile(mod
, filename
,
609 str
= source_as_string(cmd
, "compile", "string, bytes, AST or code", &cf
);
613 return Py_CompileStringFlags(str
, filename
, start
[mode
], &cf
);
616 PyDoc_STRVAR(compile_doc
,
617 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
619 Compile the source string (a Python module, statement or expression)\n\
620 into a code object that can be executed by exec() or eval().\n\
621 The filename will be used for run-time error messages.\n\
622 The mode must be 'exec' to compile a module, 'single' to compile a\n\
623 single (interactive) statement, or 'eval' to compile an expression.\n\
624 The flags argument, if present, controls which future statements influence\n\
625 the compilation of the code.\n\
626 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
627 the effects of any future statements in effect in the code calling\n\
628 compile; if absent or zero these statements do influence the compilation,\n\
629 in addition to any features explicitly specified.");
632 builtin_dir(PyObject
*self
, PyObject
*args
)
634 PyObject
*arg
= NULL
;
636 if (!PyArg_UnpackTuple(args
, "dir", 0, 1, &arg
))
638 return PyObject_Dir(arg
);
641 PyDoc_STRVAR(dir_doc
,
642 "dir([object]) -> list of strings\n"
644 "If called without an argument, return the names in the current scope.\n"
645 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
646 "of the given object, and of attributes reachable from it.\n"
647 "If the object supplies a method named __dir__, it will be used; otherwise\n"
648 "the default dir() logic is used and returns:\n"
649 " for a module object: the module's attributes.\n"
650 " for a class object: its attributes, and recursively the attributes\n"
652 " for any other object: its attributes, its class's attributes, and\n"
653 " recursively the attributes of its class's base classes.");
656 builtin_divmod(PyObject
*self
, PyObject
*args
)
660 if (!PyArg_UnpackTuple(args
, "divmod", 2, 2, &v
, &w
))
662 return PyNumber_Divmod(v
, w
);
665 PyDoc_STRVAR(divmod_doc
,
666 "divmod(x, y) -> (div, mod)\n\
668 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
672 builtin_eval(PyObject
*self
, PyObject
*args
)
674 PyObject
*cmd
, *result
, *tmp
= NULL
;
675 PyObject
*globals
= Py_None
, *locals
= Py_None
;
679 if (!PyArg_UnpackTuple(args
, "eval", 1, 3, &cmd
, &globals
, &locals
))
681 if (locals
!= Py_None
&& !PyMapping_Check(locals
)) {
682 PyErr_SetString(PyExc_TypeError
, "locals must be a mapping");
685 if (globals
!= Py_None
&& !PyDict_Check(globals
)) {
686 PyErr_SetString(PyExc_TypeError
, PyMapping_Check(globals
) ?
687 "globals must be a real dict; try eval(expr, {}, mapping)"
688 : "globals must be a dict");
691 if (globals
== Py_None
) {
692 globals
= PyEval_GetGlobals();
693 if (locals
== Py_None
)
694 locals
= PyEval_GetLocals();
696 else if (locals
== Py_None
)
699 if (globals
== NULL
|| locals
== NULL
) {
700 PyErr_SetString(PyExc_TypeError
,
701 "eval must be given globals and locals "
702 "when called without a frame");
706 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
707 if (PyDict_SetItemString(globals
, "__builtins__",
708 PyEval_GetBuiltins()) != 0)
712 if (PyCode_Check(cmd
)) {
713 if (PyCode_GetNumFree((PyCodeObject
*)cmd
) > 0) {
714 PyErr_SetString(PyExc_TypeError
,
715 "code object passed to eval() may not contain free variables");
718 return PyEval_EvalCode((PyCodeObject
*) cmd
, globals
, locals
);
721 cf
.cf_flags
= PyCF_SOURCE_IS_UTF8
;
722 str
= source_as_string(cmd
, "eval", "string, bytes or code", &cf
);
726 while (*str
== ' ' || *str
== '\t')
729 (void)PyEval_MergeCompilerFlags(&cf
);
730 result
= PyRun_StringFlags(str
, Py_eval_input
, globals
, locals
, &cf
);
735 PyDoc_STRVAR(eval_doc
,
736 "eval(source[, globals[, locals]]) -> value\n\
738 Evaluate the source in the context of globals and locals.\n\
739 The source may be a string representing a Python expression\n\
740 or a code object as returned by compile().\n\
741 The globals must be a dictionary and locals can be any mapping,\n\
742 defaulting to the current globals and locals.\n\
743 If only globals is given, locals defaults to it.\n");
746 builtin_exec(PyObject
*self
, PyObject
*args
)
749 PyObject
*prog
, *globals
= Py_None
, *locals
= Py_None
;
752 if (!PyArg_UnpackTuple(args
, "exec", 1, 3, &prog
, &globals
, &locals
))
755 if (globals
== Py_None
) {
756 globals
= PyEval_GetGlobals();
757 if (locals
== Py_None
) {
758 locals
= PyEval_GetLocals();
761 if (!globals
|| !locals
) {
762 PyErr_SetString(PyExc_SystemError
,
763 "globals and locals cannot be NULL");
767 else if (locals
== Py_None
)
770 if (!PyDict_Check(globals
)) {
771 PyErr_Format(PyExc_TypeError
, "exec() arg 2 must be a dict, not %.100s",
772 globals
->ob_type
->tp_name
);
775 if (!PyMapping_Check(locals
)) {
776 PyErr_Format(PyExc_TypeError
,
777 "arg 3 must be a mapping or None, not %.100s",
778 locals
->ob_type
->tp_name
);
781 if (PyDict_GetItemString(globals
, "__builtins__") == NULL
) {
782 if (PyDict_SetItemString(globals
, "__builtins__",
783 PyEval_GetBuiltins()) != 0)
787 if (PyCode_Check(prog
)) {
788 if (PyCode_GetNumFree((PyCodeObject
*)prog
) > 0) {
789 PyErr_SetString(PyExc_TypeError
,
790 "code object passed to exec() may not "
791 "contain free variables");
794 v
= PyEval_EvalCode((PyCodeObject
*) prog
, globals
, locals
);
799 cf
.cf_flags
= PyCF_SOURCE_IS_UTF8
;
800 str
= source_as_string(prog
, "exec",
801 "string, bytes or code", &cf
);
804 if (PyEval_MergeCompilerFlags(&cf
))
805 v
= PyRun_StringFlags(str
, Py_file_input
, globals
,
808 v
= PyRun_String(str
, Py_file_input
, globals
, locals
);
816 PyDoc_STRVAR(exec_doc
,
817 "exec(object[, globals[, locals]])\n\
819 Read and execute code from an object, which can be a string or a code\n\
821 The globals and locals are dictionaries, defaulting to the current\n\
822 globals and locals. If only globals is given, locals defaults to it.");
826 builtin_getattr(PyObject
*self
, PyObject
*args
)
828 PyObject
*v
, *result
, *dflt
= NULL
;
831 if (!PyArg_UnpackTuple(args
, "getattr", 2, 3, &v
, &name
, &dflt
))
834 if (!PyUnicode_Check(name
)) {
835 PyErr_SetString(PyExc_TypeError
,
836 "getattr(): attribute name must be string");
839 result
= PyObject_GetAttr(v
, name
);
840 if (result
== NULL
&& dflt
!= NULL
&&
841 PyErr_ExceptionMatches(PyExc_AttributeError
))
850 PyDoc_STRVAR(getattr_doc
,
851 "getattr(object, name[, default]) -> value\n\
853 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
854 When a default argument is given, it is returned when the attribute doesn't\n\
855 exist; without it, an exception is raised in that case.");
859 builtin_globals(PyObject
*self
)
863 d
= PyEval_GetGlobals();
868 PyDoc_STRVAR(globals_doc
,
869 "globals() -> dictionary\n\
871 Return the dictionary containing the current scope's global variables.");
875 builtin_hasattr(PyObject
*self
, PyObject
*args
)
880 if (!PyArg_UnpackTuple(args
, "hasattr", 2, 2, &v
, &name
))
882 if (!PyUnicode_Check(name
)) {
883 PyErr_SetString(PyExc_TypeError
,
884 "hasattr(): attribute name must be string");
887 v
= PyObject_GetAttr(v
, name
);
889 if (!PyErr_ExceptionMatches(PyExc_Exception
))
902 PyDoc_STRVAR(hasattr_doc
,
903 "hasattr(object, name) -> bool\n\
905 Return whether the object has an attribute with the given name.\n\
906 (This is done by calling getattr(object, name) and catching exceptions.)");
910 builtin_id(PyObject
*self
, PyObject
*v
)
912 return PyLong_FromVoidPtr(v
);
916 "id(object) -> integer\n\
918 Return the identity of an object. This is guaranteed to be unique among\n\
919 simultaneously existing objects. (Hint: it's the object's memory address.)");
922 /* map object ************************************************************/
931 map_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
933 PyObject
*it
, *iters
, *func
;
935 Py_ssize_t numargs
, i
;
937 if (type
== &PyMap_Type
&& !_PyArg_NoKeywords("map()", kwds
))
940 numargs
= PyTuple_Size(args
);
942 PyErr_SetString(PyExc_TypeError
,
943 "map() must have at least two arguments.");
947 iters
= PyTuple_New(numargs
-1);
951 for (i
=1 ; i
<numargs
; i
++) {
953 it
= PyObject_GetIter(PyTuple_GET_ITEM(args
, i
));
958 PyTuple_SET_ITEM(iters
, i
-1, it
);
961 /* create mapobject structure */
962 lz
= (mapobject
*)type
->tp_alloc(type
, 0);
968 func
= PyTuple_GET_ITEM(args
, 0);
972 return (PyObject
*)lz
;
976 map_dealloc(mapobject
*lz
)
978 PyObject_GC_UnTrack(lz
);
979 Py_XDECREF(lz
->iters
);
980 Py_XDECREF(lz
->func
);
981 Py_TYPE(lz
)->tp_free(lz
);
985 map_traverse(mapobject
*lz
, visitproc visit
, void *arg
)
993 map_next(mapobject
*lz
)
998 Py_ssize_t numargs
, i
;
1000 numargs
= PyTuple_Size(lz
->iters
);
1001 argtuple
= PyTuple_New(numargs
);
1002 if (argtuple
== NULL
)
1005 for (i
=0 ; i
<numargs
; i
++) {
1006 val
= PyIter_Next(PyTuple_GET_ITEM(lz
->iters
, i
));
1008 Py_DECREF(argtuple
);
1011 PyTuple_SET_ITEM(argtuple
, i
, val
);
1013 result
= PyObject_Call(lz
->func
, argtuple
, NULL
);
1014 Py_DECREF(argtuple
);
1018 PyDoc_STRVAR(map_doc
,
1019 "map(func, *iterables) --> map object\n\
1021 Make an iterator that computes the function using arguments from\n\
1022 each of the iterables. Stops when the shortest iterable is exhausted.");
1024 PyTypeObject PyMap_Type
= {
1025 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
1026 "map", /* tp_name */
1027 sizeof(mapobject
), /* tp_basicsize */
1028 0, /* tp_itemsize */
1030 (destructor
)map_dealloc
, /* tp_dealloc */
1034 0, /* tp_reserved */
1036 0, /* tp_as_number */
1037 0, /* tp_as_sequence */
1038 0, /* tp_as_mapping */
1042 PyObject_GenericGetAttr
, /* tp_getattro */
1043 0, /* tp_setattro */
1044 0, /* tp_as_buffer */
1045 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
1046 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1047 map_doc
, /* tp_doc */
1048 (traverseproc
)map_traverse
, /* tp_traverse */
1050 0, /* tp_richcompare */
1051 0, /* tp_weaklistoffset */
1052 PyObject_SelfIter
, /* tp_iter */
1053 (iternextfunc
)map_next
, /* tp_iternext */
1059 0, /* tp_descr_get */
1060 0, /* tp_descr_set */
1061 0, /* tp_dictoffset */
1063 PyType_GenericAlloc
, /* tp_alloc */
1064 map_new
, /* tp_new */
1065 PyObject_GC_Del
, /* tp_free */
1069 builtin_next(PyObject
*self
, PyObject
*args
)
1072 PyObject
*def
= NULL
;
1074 if (!PyArg_UnpackTuple(args
, "next", 1, 2, &it
, &def
))
1076 if (!PyIter_Check(it
)) {
1077 PyErr_Format(PyExc_TypeError
,
1078 "%.200s object is not an iterator",
1079 it
->ob_type
->tp_name
);
1083 res
= (*it
->ob_type
->tp_iternext
)(it
);
1086 } else if (def
!= NULL
) {
1087 if (PyErr_Occurred()) {
1088 if(!PyErr_ExceptionMatches(PyExc_StopIteration
))
1094 } else if (PyErr_Occurred()) {
1097 PyErr_SetNone(PyExc_StopIteration
);
1102 PyDoc_STRVAR(next_doc
,
1103 "next(iterator[, default])\n\
1105 Return the next item from the iterator. If default is given and the iterator\n\
1106 is exhausted, it is returned instead of raising StopIteration.");
1110 builtin_setattr(PyObject
*self
, PyObject
*args
)
1116 if (!PyArg_UnpackTuple(args
, "setattr", 3, 3, &v
, &name
, &value
))
1118 if (PyObject_SetAttr(v
, name
, value
) != 0)
1124 PyDoc_STRVAR(setattr_doc
,
1125 "setattr(object, name, value)\n\
1127 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1132 builtin_delattr(PyObject
*self
, PyObject
*args
)
1137 if (!PyArg_UnpackTuple(args
, "delattr", 2, 2, &v
, &name
))
1139 if (PyObject_SetAttr(v
, name
, (PyObject
*)NULL
) != 0)
1145 PyDoc_STRVAR(delattr_doc
,
1146 "delattr(object, name)\n\
1148 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1153 builtin_hash(PyObject
*self
, PyObject
*v
)
1157 x
= PyObject_Hash(v
);
1160 return PyLong_FromLong(x
);
1163 PyDoc_STRVAR(hash_doc
,
1164 "hash(object) -> integer\n\
1166 Return a hash value for the object. Two objects with the same value have\n\
1167 the same hash value. The reverse is not necessarily true, but likely.");
1171 builtin_hex(PyObject
*self
, PyObject
*v
)
1173 return PyNumber_ToBase(v
, 16);
1176 PyDoc_STRVAR(hex_doc
,
1177 "hex(number) -> string\n\
1179 Return the hexadecimal representation of an integer or long integer.");
1183 builtin_iter(PyObject
*self
, PyObject
*args
)
1185 PyObject
*v
, *w
= NULL
;
1187 if (!PyArg_UnpackTuple(args
, "iter", 1, 2, &v
, &w
))
1190 return PyObject_GetIter(v
);
1191 if (!PyCallable_Check(v
)) {
1192 PyErr_SetString(PyExc_TypeError
,
1193 "iter(v, w): v must be callable");
1196 return PyCallIter_New(v
, w
);
1199 PyDoc_STRVAR(iter_doc
,
1200 "iter(iterable) -> iterator\n\
1201 iter(callable, sentinel) -> iterator\n\
1203 Get an iterator from an object. In the first form, the argument must\n\
1204 supply its own iterator, or be a sequence.\n\
1205 In the second form, the callable is called until it returns the sentinel.");
1209 builtin_len(PyObject
*self
, PyObject
*v
)
1213 res
= PyObject_Size(v
);
1214 if (res
< 0 && PyErr_Occurred())
1216 return PyLong_FromSsize_t(res
);
1219 PyDoc_STRVAR(len_doc
,
1220 "len(object) -> integer\n\
1222 Return the number of items of a sequence or mapping.");
1226 builtin_locals(PyObject
*self
)
1230 d
= PyEval_GetLocals();
1235 PyDoc_STRVAR(locals_doc
,
1236 "locals() -> dictionary\n\
1238 Update and return a dictionary containing the current scope's local variables.");
1242 min_max(PyObject
*args
, PyObject
*kwds
, int op
)
1244 PyObject
*v
, *it
, *item
, *val
, *maxitem
, *maxval
, *keyfunc
=NULL
;
1245 const char *name
= op
== Py_LT
? "min" : "max";
1247 if (PyTuple_Size(args
) > 1)
1249 else if (!PyArg_UnpackTuple(args
, (char *)name
, 1, 1, &v
))
1252 if (kwds
!= NULL
&& PyDict_Check(kwds
) && PyDict_Size(kwds
)) {
1253 keyfunc
= PyDict_GetItemString(kwds
, "key");
1254 if (PyDict_Size(kwds
)!=1 || keyfunc
== NULL
) {
1255 PyErr_Format(PyExc_TypeError
,
1256 "%s() got an unexpected keyword argument", name
);
1262 it
= PyObject_GetIter(v
);
1264 Py_XDECREF(keyfunc
);
1268 maxitem
= NULL
; /* the result */
1269 maxval
= NULL
; /* the value associated with the result */
1270 while (( item
= PyIter_Next(it
) )) {
1271 /* get the value from the key function */
1272 if (keyfunc
!= NULL
) {
1273 val
= PyObject_CallFunctionObjArgs(keyfunc
, item
, NULL
);
1277 /* no key function; the value is the item */
1283 /* maximum value and item are unset; set them */
1284 if (maxval
== NULL
) {
1288 /* maximum value and item are set; update them as necessary */
1290 int cmp
= PyObject_RichCompareBool(val
, maxval
, op
);
1292 goto Fail_it_item_and_val
;
1305 if (PyErr_Occurred())
1307 if (maxval
== NULL
) {
1308 PyErr_Format(PyExc_ValueError
,
1309 "%s() arg is an empty sequence", name
);
1310 assert(maxitem
== NULL
);
1315 Py_XDECREF(keyfunc
);
1318 Fail_it_item_and_val
:
1324 Py_XDECREF(maxitem
);
1326 Py_XDECREF(keyfunc
);
1331 builtin_min(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1333 return min_max(args
, kwds
, Py_LT
);
1336 PyDoc_STRVAR(min_doc
,
1337 "min(iterable[, key=func]) -> value\n\
1338 min(a, b, c, ...[, key=func]) -> value\n\
1340 With a single iterable argument, return its smallest item.\n\
1341 With two or more arguments, return the smallest argument.");
1345 builtin_max(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1347 return min_max(args
, kwds
, Py_GT
);
1350 PyDoc_STRVAR(max_doc
,
1351 "max(iterable[, key=func]) -> value\n\
1352 max(a, b, c, ...[, key=func]) -> value\n\
1354 With a single iterable argument, return its largest item.\n\
1355 With two or more arguments, return the largest argument.");
1359 builtin_oct(PyObject
*self
, PyObject
*v
)
1361 return PyNumber_ToBase(v
, 8);
1364 PyDoc_STRVAR(oct_doc
,
1365 "oct(number) -> string\n\
1367 Return the octal representation of an integer or long integer.");
1371 builtin_ord(PyObject
*self
, PyObject
* obj
)
1376 if (PyBytes_Check(obj
)) {
1377 size
= PyBytes_GET_SIZE(obj
);
1379 ord
= (long)((unsigned char)*PyBytes_AS_STRING(obj
));
1380 return PyLong_FromLong(ord
);
1383 else if (PyUnicode_Check(obj
)) {
1384 size
= PyUnicode_GET_SIZE(obj
);
1386 ord
= (long)*PyUnicode_AS_UNICODE(obj
);
1387 return PyLong_FromLong(ord
);
1389 #ifndef Py_UNICODE_WIDE
1391 /* Decode a valid surrogate pair */
1392 int c0
= PyUnicode_AS_UNICODE(obj
)[0];
1393 int c1
= PyUnicode_AS_UNICODE(obj
)[1];
1394 if (0xD800 <= c0
&& c0
<= 0xDBFF &&
1395 0xDC00 <= c1
&& c1
<= 0xDFFF) {
1396 ord
= ((((c0
& 0x03FF) << 10) | (c1
& 0x03FF)) +
1398 return PyLong_FromLong(ord
);
1403 else if (PyByteArray_Check(obj
)) {
1404 /* XXX Hopefully this is temporary */
1405 size
= PyByteArray_GET_SIZE(obj
);
1407 ord
= (long)((unsigned char)*PyByteArray_AS_STRING(obj
));
1408 return PyLong_FromLong(ord
);
1412 PyErr_Format(PyExc_TypeError
,
1413 "ord() expected string of length 1, but " \
1414 "%.200s found", obj
->ob_type
->tp_name
);
1418 PyErr_Format(PyExc_TypeError
,
1419 "ord() expected a character, "
1420 "but string of length %zd found",
1425 PyDoc_VAR(ord_doc
) = PyDoc_STR(
1426 "ord(c) -> integer\n\
1428 Return the integer ordinal of a one-character string."
1430 #ifndef Py_UNICODE_WIDE
1432 "\nA valid surrogate pair is also accepted."
1439 builtin_pow(PyObject
*self
, PyObject
*args
)
1441 PyObject
*v
, *w
, *z
= Py_None
;
1443 if (!PyArg_UnpackTuple(args
, "pow", 2, 3, &v
, &w
, &z
))
1445 return PyNumber_Power(v
, w
, z
);
1448 PyDoc_STRVAR(pow_doc
,
1449 "pow(x, y[, z]) -> number\n\
1451 With two arguments, equivalent to x**y. With three arguments,\n\
1452 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1457 builtin_print(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1459 static char *kwlist
[] = {"sep", "end", "file", 0};
1460 static PyObject
*dummy_args
;
1461 PyObject
*sep
= NULL
, *end
= NULL
, *file
= NULL
;
1464 if (dummy_args
== NULL
) {
1465 if (!(dummy_args
= PyTuple_New(0)))
1468 if (!PyArg_ParseTupleAndKeywords(dummy_args
, kwds
, "|OOO:print",
1469 kwlist
, &sep
, &end
, &file
))
1471 if (file
== NULL
|| file
== Py_None
) {
1472 file
= PySys_GetObject("stdout");
1473 /* sys.stdout may be None when FILE* stdout isn't connected */
1474 if (file
== Py_None
)
1478 if (sep
&& sep
!= Py_None
&& !PyUnicode_Check(sep
)) {
1479 PyErr_Format(PyExc_TypeError
,
1480 "sep must be None or a string, not %.200s",
1481 sep
->ob_type
->tp_name
);
1484 if (end
&& end
!= Py_None
&& !PyUnicode_Check(end
)) {
1485 PyErr_Format(PyExc_TypeError
,
1486 "end must be None or a string, not %.200s",
1487 end
->ob_type
->tp_name
);
1491 for (i
= 0; i
< PyTuple_Size(args
); i
++) {
1493 if (sep
== NULL
|| sep
== Py_None
)
1494 err
= PyFile_WriteString(" ", file
);
1496 err
= PyFile_WriteObject(sep
, file
,
1501 err
= PyFile_WriteObject(PyTuple_GetItem(args
, i
), file
,
1507 if (end
== NULL
|| end
== Py_None
)
1508 err
= PyFile_WriteString("\n", file
);
1510 err
= PyFile_WriteObject(end
, file
, Py_PRINT_RAW
);
1517 PyDoc_STRVAR(print_doc
,
1518 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1520 Prints the values to a stream, or to sys.stdout by default.\n\
1521 Optional keyword arguments:\n\
1522 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1523 sep: string inserted between values, default a space.\n\
1524 end: string appended after the last value, default a newline.");
1528 builtin_input(PyObject
*self
, PyObject
*args
)
1530 PyObject
*promptarg
= NULL
;
1531 PyObject
*fin
= PySys_GetObject("stdin");
1532 PyObject
*fout
= PySys_GetObject("stdout");
1533 PyObject
*ferr
= PySys_GetObject("stderr");
1538 /* Parse arguments */
1539 if (!PyArg_UnpackTuple(args
, "input", 0, 1, &promptarg
))
1542 /* Check that stdin/out/err are intact */
1543 if (fin
== NULL
|| fin
== Py_None
) {
1544 PyErr_SetString(PyExc_RuntimeError
,
1545 "input(): lost sys.stdin");
1548 if (fout
== NULL
|| fout
== Py_None
) {
1549 PyErr_SetString(PyExc_RuntimeError
,
1550 "input(): lost sys.stdout");
1553 if (ferr
== NULL
|| ferr
== Py_None
) {
1554 PyErr_SetString(PyExc_RuntimeError
,
1555 "input(): lost sys.stderr");
1559 /* First of all, flush stderr */
1560 tmp
= PyObject_CallMethod(ferr
, "flush", "");
1566 /* We should only use (GNU) readline if Python's sys.stdin and
1567 sys.stdout are the same as C's stdin and stdout, because we
1568 need to pass it those. */
1569 tmp
= PyObject_CallMethod(fin
, "fileno", "");
1575 fd
= PyLong_AsLong(tmp
);
1577 if (fd
< 0 && PyErr_Occurred())
1579 tty
= fd
== fileno(stdin
) && isatty(fd
);
1582 tmp
= PyObject_CallMethod(fout
, "fileno", "");
1586 fd
= PyLong_AsLong(tmp
);
1588 if (fd
< 0 && PyErr_Occurred())
1590 tty
= fd
== fileno(stdout
) && isatty(fd
);
1594 /* If we're interactive, use (GNU) readline */
1599 PyObject
*stdin_encoding
;
1602 stdin_encoding
= PyObject_GetAttrString(fin
, "encoding");
1603 if (!stdin_encoding
)
1604 /* stdin is a text stream, so it must have an
1607 tmp
= PyObject_CallMethod(fout
, "flush", "");
1612 if (promptarg
!= NULL
) {
1614 PyObject
*stdout_encoding
;
1615 stdout_encoding
= PyObject_GetAttrString(fout
,
1617 if (stdout_encoding
== NULL
) {
1618 Py_DECREF(stdin_encoding
);
1621 stringpo
= PyObject_Str(promptarg
);
1622 if (stringpo
== NULL
) {
1623 Py_DECREF(stdin_encoding
);
1624 Py_DECREF(stdout_encoding
);
1627 po
= PyUnicode_AsEncodedString(stringpo
,
1628 _PyUnicode_AsString(stdout_encoding
), NULL
);
1629 Py_DECREF(stdout_encoding
);
1630 Py_DECREF(stringpo
);
1632 Py_DECREF(stdin_encoding
);
1635 prompt
= PyBytes_AsString(po
);
1636 if (prompt
== NULL
) {
1637 Py_DECREF(stdin_encoding
);
1646 s
= PyOS_Readline(stdin
, stdout
, prompt
);
1649 if (!PyErr_Occurred())
1650 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1651 Py_DECREF(stdin_encoding
);
1655 PyErr_SetNone(PyExc_EOFError
);
1658 else { /* strip trailing '\n' */
1659 size_t len
= strlen(s
);
1660 if (len
> PY_SSIZE_T_MAX
) {
1661 PyErr_SetString(PyExc_OverflowError
,
1662 "input: input too long");
1666 result
= PyUnicode_Decode
1668 _PyUnicode_AsString(stdin_encoding
),
1672 Py_DECREF(stdin_encoding
);
1677 /* Fallback if we're not interactive */
1678 if (promptarg
!= NULL
) {
1679 if (PyFile_WriteObject(promptarg
, fout
, Py_PRINT_RAW
) != 0)
1682 tmp
= PyObject_CallMethod(fout
, "flush", "");
1687 return PyFile_GetLine(fin
, -1);
1690 PyDoc_STRVAR(input_doc
,
1691 "input([prompt]) -> string\n\
1693 Read a string from standard input. The trailing newline is stripped.\n\
1694 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1695 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1696 is printed without a trailing newline before reading.");
1700 builtin_repr(PyObject
*self
, PyObject
*v
)
1702 return PyObject_Repr(v
);
1705 PyDoc_STRVAR(repr_doc
,
1706 "repr(object) -> string\n\
1708 Return the canonical string representation of the object.\n\
1709 For most object types, eval(repr(object)) == object.");
1713 builtin_round(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1715 static PyObject
*round_str
= NULL
;
1716 PyObject
*ndigits
= NULL
;
1717 static char *kwlist
[] = {"number", "ndigits", 0};
1718 PyObject
*number
, *round
;
1720 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|O:round",
1721 kwlist
, &number
, &ndigits
))
1724 if (Py_TYPE(number
)->tp_dict
== NULL
) {
1725 if (PyType_Ready(Py_TYPE(number
)) < 0)
1729 if (round_str
== NULL
) {
1730 round_str
= PyUnicode_InternFromString("__round__");
1731 if (round_str
== NULL
)
1735 round
= _PyType_Lookup(Py_TYPE(number
), round_str
);
1736 if (round
== NULL
) {
1737 PyErr_Format(PyExc_TypeError
,
1738 "type %.100s doesn't define __round__ method",
1739 Py_TYPE(number
)->tp_name
);
1743 if (ndigits
== NULL
)
1744 return PyObject_CallFunction(round
, "O", number
);
1746 return PyObject_CallFunction(round
, "OO", number
, ndigits
);
1749 PyDoc_STRVAR(round_doc
,
1750 "round(number[, ndigits]) -> number\n\
1752 Round a number to a given precision in decimal digits (default 0 digits).\n\
1753 This returns an int when called with one argument, otherwise the\n\
1754 same type as the number. ndigits may be negative.");
1758 builtin_sorted(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1760 PyObject
*newlist
, *v
, *seq
, *keyfunc
=NULL
, *newargs
;
1762 static char *kwlist
[] = {"iterable", "key", "reverse", 0};
1765 /* args 1-3 should match listsort in Objects/listobject.c */
1766 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|Oi:sorted",
1767 kwlist
, &seq
, &keyfunc
, &reverse
))
1770 newlist
= PySequence_List(seq
);
1771 if (newlist
== NULL
)
1774 callable
= PyObject_GetAttrString(newlist
, "sort");
1775 if (callable
== NULL
) {
1780 newargs
= PyTuple_GetSlice(args
, 1, 4);
1781 if (newargs
== NULL
) {
1783 Py_DECREF(callable
);
1787 v
= PyObject_Call(callable
, newargs
, kwds
);
1789 Py_DECREF(callable
);
1798 PyDoc_STRVAR(sorted_doc
,
1799 "sorted(iterable, key=None, reverse=False) --> new sorted list");
1802 builtin_vars(PyObject
*self
, PyObject
*args
)
1807 if (!PyArg_UnpackTuple(args
, "vars", 0, 1, &v
))
1810 d
= PyEval_GetLocals();
1812 if (!PyErr_Occurred())
1813 PyErr_SetString(PyExc_SystemError
,
1814 "vars(): no locals!?");
1820 d
= PyObject_GetAttrString(v
, "__dict__");
1822 PyErr_SetString(PyExc_TypeError
,
1823 "vars() argument must have __dict__ attribute");
1830 PyDoc_STRVAR(vars_doc
,
1831 "vars([object]) -> dictionary\n\
1833 Without arguments, equivalent to locals().\n\
1834 With an argument, equivalent to object.__dict__.");
1837 builtin_sum(PyObject
*self
, PyObject
*args
)
1840 PyObject
*result
= NULL
;
1841 PyObject
*temp
, *item
, *iter
;
1843 if (!PyArg_UnpackTuple(args
, "sum", 1, 2, &seq
, &result
))
1846 iter
= PyObject_GetIter(seq
);
1850 if (result
== NULL
) {
1851 result
= PyLong_FromLong(0);
1852 if (result
== NULL
) {
1857 /* reject string values for 'start' parameter */
1858 if (PyUnicode_Check(result
)) {
1859 PyErr_SetString(PyExc_TypeError
,
1860 "sum() can't sum strings [use ''.join(seq) instead]");
1864 if (PyByteArray_Check(result
)) {
1865 PyErr_SetString(PyExc_TypeError
,
1866 "sum() can't sum bytes [use b''.join(seq) instead]");
1875 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1876 Assumes all inputs are the same type. If the assumption fails, default
1877 to the more general routine.
1879 if (PyLong_CheckExact(result
)) {
1881 long i_result
= PyLong_AsLongAndOverflow(result
, &overflow
);
1882 /* If this already overflowed, don't even enter the loop. */
1883 if (overflow
== 0) {
1887 while(result
== NULL
) {
1888 item
= PyIter_Next(iter
);
1891 if (PyErr_Occurred())
1893 return PyLong_FromLong(i_result
);
1895 if (PyLong_CheckExact(item
)) {
1896 long b
= PyLong_AsLongAndOverflow(item
, &overflow
);
1897 long x
= i_result
+ b
;
1898 if (overflow
== 0 && ((x
^i_result
) >= 0 || (x
^b
) >= 0)) {
1904 /* Either overflowed or is not an int. Restore real objects and process normally */
1905 result
= PyLong_FromLong(i_result
);
1906 temp
= PyNumber_Add(result
, item
);
1910 if (result
== NULL
) {
1917 if (PyFloat_CheckExact(result
)) {
1918 double f_result
= PyFloat_AS_DOUBLE(result
);
1921 while(result
== NULL
) {
1922 item
= PyIter_Next(iter
);
1925 if (PyErr_Occurred())
1927 return PyFloat_FromDouble(f_result
);
1929 if (PyFloat_CheckExact(item
)) {
1930 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
1931 f_result
+= PyFloat_AS_DOUBLE(item
);
1932 PyFPE_END_PROTECT(f_result
)
1936 if (PyLong_CheckExact(item
)) {
1939 value
= PyLong_AsLongAndOverflow(item
, &overflow
);
1941 PyFPE_START_PROTECT("add", Py_DECREF(item
); Py_DECREF(iter
); return 0)
1942 f_result
+= (double)value
;
1943 PyFPE_END_PROTECT(f_result
)
1948 result
= PyFloat_FromDouble(f_result
);
1949 temp
= PyNumber_Add(result
, item
);
1953 if (result
== NULL
) {
1962 item
= PyIter_Next(iter
);
1964 /* error, or end-of-sequence */
1965 if (PyErr_Occurred()) {
1971 temp
= PyNumber_Add(result
, item
);
1982 PyDoc_STRVAR(sum_doc
,
1983 "sum(iterable[, start]) -> value\n\
1985 Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
1986 of parameter 'start' (which defaults to 0). When the iterable is\n\
1987 empty, returns start.");
1991 builtin_isinstance(PyObject
*self
, PyObject
*args
)
1997 if (!PyArg_UnpackTuple(args
, "isinstance", 2, 2, &inst
, &cls
))
2000 retval
= PyObject_IsInstance(inst
, cls
);
2003 return PyBool_FromLong(retval
);
2006 PyDoc_STRVAR(isinstance_doc
,
2007 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2009 Return whether an object is an instance of a class or of a subclass thereof.\n\
2010 With a type as second argument, return whether that is the object's type.\n\
2011 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2012 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2016 builtin_issubclass(PyObject
*self
, PyObject
*args
)
2022 if (!PyArg_UnpackTuple(args
, "issubclass", 2, 2, &derived
, &cls
))
2025 retval
= PyObject_IsSubclass(derived
, cls
);
2028 return PyBool_FromLong(retval
);
2031 PyDoc_STRVAR(issubclass_doc
,
2032 "issubclass(C, B) -> bool\n\
2034 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2035 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2036 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2041 Py_ssize_t tuplesize
;
2042 PyObject
*ittuple
; /* tuple of iterators */
2047 zip_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2051 PyObject
*ittuple
; /* tuple of iterators */
2053 Py_ssize_t tuplesize
= PySequence_Length(args
);
2055 if (type
== &PyZip_Type
&& !_PyArg_NoKeywords("zip()", kwds
))
2058 /* args must be a tuple */
2059 assert(PyTuple_Check(args
));
2061 /* obtain iterators */
2062 ittuple
= PyTuple_New(tuplesize
);
2063 if (ittuple
== NULL
)
2065 for (i
=0; i
< tuplesize
; ++i
) {
2066 PyObject
*item
= PyTuple_GET_ITEM(args
, i
);
2067 PyObject
*it
= PyObject_GetIter(item
);
2069 if (PyErr_ExceptionMatches(PyExc_TypeError
))
2070 PyErr_Format(PyExc_TypeError
,
2071 "zip argument #%zd must support iteration",
2076 PyTuple_SET_ITEM(ittuple
, i
, it
);
2079 /* create a result holder */
2080 result
= PyTuple_New(tuplesize
);
2081 if (result
== NULL
) {
2085 for (i
=0 ; i
< tuplesize
; i
++) {
2087 PyTuple_SET_ITEM(result
, i
, Py_None
);
2090 /* create zipobject structure */
2091 lz
= (zipobject
*)type
->tp_alloc(type
, 0);
2097 lz
->ittuple
= ittuple
;
2098 lz
->tuplesize
= tuplesize
;
2099 lz
->result
= result
;
2101 return (PyObject
*)lz
;
2105 zip_dealloc(zipobject
*lz
)
2107 PyObject_GC_UnTrack(lz
);
2108 Py_XDECREF(lz
->ittuple
);
2109 Py_XDECREF(lz
->result
);
2110 Py_TYPE(lz
)->tp_free(lz
);
2114 zip_traverse(zipobject
*lz
, visitproc visit
, void *arg
)
2116 Py_VISIT(lz
->ittuple
);
2117 Py_VISIT(lz
->result
);
2122 zip_next(zipobject
*lz
)
2125 Py_ssize_t tuplesize
= lz
->tuplesize
;
2126 PyObject
*result
= lz
->result
;
2133 if (Py_REFCNT(result
) == 1) {
2135 for (i
=0 ; i
< tuplesize
; i
++) {
2136 it
= PyTuple_GET_ITEM(lz
->ittuple
, i
);
2137 item
= (*Py_TYPE(it
)->tp_iternext
)(it
);
2142 olditem
= PyTuple_GET_ITEM(result
, i
);
2143 PyTuple_SET_ITEM(result
, i
, item
);
2147 result
= PyTuple_New(tuplesize
);
2150 for (i
=0 ; i
< tuplesize
; i
++) {
2151 it
= PyTuple_GET_ITEM(lz
->ittuple
, i
);
2152 item
= (*Py_TYPE(it
)->tp_iternext
)(it
);
2157 PyTuple_SET_ITEM(result
, i
, item
);
2163 PyDoc_STRVAR(zip_doc
,
2164 "zip(iter1 [,iter2 [...]]) --> zip object\n\
2166 Return a zip object whose .__next__() method returns a tuple where\n\
2167 the i-th element comes from the i-th iterable argument. The .__next__()\n\
2168 method continues until the shortest iterable in the argument sequence\n\
2169 is exhausted and then it raises StopIteration.");
2171 PyTypeObject PyZip_Type
= {
2172 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
2173 "zip", /* tp_name */
2174 sizeof(zipobject
), /* tp_basicsize */
2175 0, /* tp_itemsize */
2177 (destructor
)zip_dealloc
, /* tp_dealloc */
2181 0, /* tp_reserved */
2183 0, /* tp_as_number */
2184 0, /* tp_as_sequence */
2185 0, /* tp_as_mapping */
2189 PyObject_GenericGetAttr
, /* tp_getattro */
2190 0, /* tp_setattro */
2191 0, /* tp_as_buffer */
2192 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
2193 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2194 zip_doc
, /* tp_doc */
2195 (traverseproc
)zip_traverse
, /* tp_traverse */
2197 0, /* tp_richcompare */
2198 0, /* tp_weaklistoffset */
2199 PyObject_SelfIter
, /* tp_iter */
2200 (iternextfunc
)zip_next
, /* tp_iternext */
2206 0, /* tp_descr_get */
2207 0, /* tp_descr_set */
2208 0, /* tp_dictoffset */
2210 PyType_GenericAlloc
, /* tp_alloc */
2211 zip_new
, /* tp_new */
2212 PyObject_GC_Del
, /* tp_free */
2216 static PyMethodDef builtin_methods
[] = {
2217 {"__build_class__", (PyCFunction
)builtin___build_class__
,
2218 METH_VARARGS
| METH_KEYWORDS
, build_class_doc
},
2219 {"__import__", (PyCFunction
)builtin___import__
, METH_VARARGS
| METH_KEYWORDS
, import_doc
},
2220 {"abs", builtin_abs
, METH_O
, abs_doc
},
2221 {"all", builtin_all
, METH_O
, all_doc
},
2222 {"any", builtin_any
, METH_O
, any_doc
},
2223 {"ascii", builtin_ascii
, METH_O
, ascii_doc
},
2224 {"bin", builtin_bin
, METH_O
, bin_doc
},
2225 {"chr", builtin_chr
, METH_VARARGS
, chr_doc
},
2226 {"compile", (PyCFunction
)builtin_compile
, METH_VARARGS
| METH_KEYWORDS
, compile_doc
},
2227 {"delattr", builtin_delattr
, METH_VARARGS
, delattr_doc
},
2228 {"dir", builtin_dir
, METH_VARARGS
, dir_doc
},
2229 {"divmod", builtin_divmod
, METH_VARARGS
, divmod_doc
},
2230 {"eval", builtin_eval
, METH_VARARGS
, eval_doc
},
2231 {"exec", builtin_exec
, METH_VARARGS
, exec_doc
},
2232 {"format", builtin_format
, METH_VARARGS
, format_doc
},
2233 {"getattr", builtin_getattr
, METH_VARARGS
, getattr_doc
},
2234 {"globals", (PyCFunction
)builtin_globals
, METH_NOARGS
, globals_doc
},
2235 {"hasattr", builtin_hasattr
, METH_VARARGS
, hasattr_doc
},
2236 {"hash", builtin_hash
, METH_O
, hash_doc
},
2237 {"hex", builtin_hex
, METH_O
, hex_doc
},
2238 {"id", builtin_id
, METH_O
, id_doc
},
2239 {"input", builtin_input
, METH_VARARGS
, input_doc
},
2240 {"isinstance", builtin_isinstance
, METH_VARARGS
, isinstance_doc
},
2241 {"issubclass", builtin_issubclass
, METH_VARARGS
, issubclass_doc
},
2242 {"iter", builtin_iter
, METH_VARARGS
, iter_doc
},
2243 {"len", builtin_len
, METH_O
, len_doc
},
2244 {"locals", (PyCFunction
)builtin_locals
, METH_NOARGS
, locals_doc
},
2245 {"max", (PyCFunction
)builtin_max
, METH_VARARGS
| METH_KEYWORDS
, max_doc
},
2246 {"min", (PyCFunction
)builtin_min
, METH_VARARGS
| METH_KEYWORDS
, min_doc
},
2247 {"next", (PyCFunction
)builtin_next
, METH_VARARGS
, next_doc
},
2248 {"oct", builtin_oct
, METH_O
, oct_doc
},
2249 {"ord", builtin_ord
, METH_O
, ord_doc
},
2250 {"pow", builtin_pow
, METH_VARARGS
, pow_doc
},
2251 {"print", (PyCFunction
)builtin_print
, METH_VARARGS
| METH_KEYWORDS
, print_doc
},
2252 {"repr", builtin_repr
, METH_O
, repr_doc
},
2253 {"round", (PyCFunction
)builtin_round
, METH_VARARGS
| METH_KEYWORDS
, round_doc
},
2254 {"setattr", builtin_setattr
, METH_VARARGS
, setattr_doc
},
2255 {"sorted", (PyCFunction
)builtin_sorted
, METH_VARARGS
| METH_KEYWORDS
, sorted_doc
},
2256 {"sum", builtin_sum
, METH_VARARGS
, sum_doc
},
2257 {"vars", builtin_vars
, METH_VARARGS
, vars_doc
},
2261 PyDoc_STRVAR(builtin_doc
,
2262 "Built-in functions, exceptions, and other objects.\n\
2264 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2266 static struct PyModuleDef builtinsmodule
= {
2267 PyModuleDef_HEAD_INIT
,
2270 -1, /* multiple "initialization" just copies the module dict. */
2280 _PyBuiltin_Init(void)
2282 PyObject
*mod
, *dict
, *debug
;
2283 mod
= PyModule_Create(&builtinsmodule
);
2286 dict
= PyModule_GetDict(mod
);
2288 #ifdef Py_TRACE_REFS
2289 /* "builtins" exposes a number of statically allocated objects
2290 * that, before this code was added in 2.3, never showed up in
2291 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2292 * result, programs leaking references to None and False (etc)
2293 * couldn't be diagnosed by examining sys.getobjects(0).
2295 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2297 #define ADD_TO_ALL(OBJECT) (void)0
2300 #define SETBUILTIN(NAME, OBJECT) \
2301 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2305 SETBUILTIN("None", Py_None
);
2306 SETBUILTIN("Ellipsis", Py_Ellipsis
);
2307 SETBUILTIN("NotImplemented", Py_NotImplemented
);
2308 SETBUILTIN("False", Py_False
);
2309 SETBUILTIN("True", Py_True
);
2310 SETBUILTIN("bool", &PyBool_Type
);
2311 SETBUILTIN("memoryview", &PyMemoryView_Type
);
2312 SETBUILTIN("bytearray", &PyByteArray_Type
);
2313 SETBUILTIN("bytes", &PyBytes_Type
);
2314 SETBUILTIN("classmethod", &PyClassMethod_Type
);
2315 #ifndef WITHOUT_COMPLEX
2316 SETBUILTIN("complex", &PyComplex_Type
);
2318 SETBUILTIN("dict", &PyDict_Type
);
2319 SETBUILTIN("enumerate", &PyEnum_Type
);
2320 SETBUILTIN("filter", &PyFilter_Type
);
2321 SETBUILTIN("float", &PyFloat_Type
);
2322 SETBUILTIN("frozenset", &PyFrozenSet_Type
);
2323 SETBUILTIN("property", &PyProperty_Type
);
2324 SETBUILTIN("int", &PyLong_Type
);
2325 SETBUILTIN("list", &PyList_Type
);
2326 SETBUILTIN("map", &PyMap_Type
);
2327 SETBUILTIN("object", &PyBaseObject_Type
);
2328 SETBUILTIN("range", &PyRange_Type
);
2329 SETBUILTIN("reversed", &PyReversed_Type
);
2330 SETBUILTIN("set", &PySet_Type
);
2331 SETBUILTIN("slice", &PySlice_Type
);
2332 SETBUILTIN("staticmethod", &PyStaticMethod_Type
);
2333 SETBUILTIN("str", &PyUnicode_Type
);
2334 SETBUILTIN("super", &PySuper_Type
);
2335 SETBUILTIN("tuple", &PyTuple_Type
);
2336 SETBUILTIN("type", &PyType_Type
);
2337 SETBUILTIN("zip", &PyZip_Type
);
2338 debug
= PyBool_FromLong(Py_OptimizeFlag
== 0);
2339 if (PyDict_SetItemString(dict
, "__debug__", debug
) < 0) {