Merged revisions 80112 via svnmerge from
[python/dscho.git] / Python / bltinmodule.c
blob10527c1428bafb92e44688d7e6467c20e7c23756
1 /* Built-in functions */
3 #include "Python.h"
4 #include "Python-ast.h"
6 #include "node.h"
7 #include "code.h"
8 #include "eval.h"
10 #include <ctype.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;
24 #else
25 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26 int Py_HasFileSystemDefaultEncoding = 0;
27 #endif
29 int
30 _Py_SetFileSystemEncoding(PyObject *s)
32 PyObject *defenc, *codec;
33 if (!PyUnicode_Check(s)) {
34 PyErr_BadInternalCall();
35 return -1;
37 defenc = _PyUnicode_AsDefaultEncodedString(s, NULL);
38 if (!defenc)
39 return -1;
40 codec = _PyCodec_Lookup(PyBytes_AsString(defenc));
41 if (codec == NULL)
42 return -1;
43 Py_DECREF(codec);
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;
49 return 0;
52 static PyObject *
53 builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
55 PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
56 PyObject *cls = NULL;
57 Py_ssize_t nargs, nbases;
59 assert(args != NULL);
60 if (!PyTuple_Check(args)) {
61 PyErr_SetString(PyExc_TypeError,
62 "__build_class__: args is not a tuple");
63 return NULL;
65 nargs = PyTuple_GET_SIZE(args);
66 if (nargs < 2) {
67 PyErr_SetString(PyExc_TypeError,
68 "__build_class__: not enough arguments");
69 return NULL;
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");
76 return NULL;
78 bases = PyTuple_GetSlice(args, 2, nargs);
79 if (bases == NULL)
80 return NULL;
81 nbases = nargs - 2;
83 if (kwds == NULL) {
84 meta = NULL;
85 mkw = NULL;
87 else {
88 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
89 if (mkw == NULL) {
90 Py_DECREF(bases);
91 return NULL;
93 meta = PyDict_GetItemString(mkw, "metaclass");
94 if (meta != NULL) {
95 Py_INCREF(meta);
96 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
97 Py_DECREF(meta);
98 Py_DECREF(mkw);
99 Py_DECREF(bases);
100 return NULL;
104 if (meta == NULL) {
105 if (PyTuple_GET_SIZE(bases) == 0)
106 meta = (PyObject *) (&PyType_Type);
107 else {
108 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
109 meta = (PyObject *) (base0->ob_type);
111 Py_INCREF(meta);
113 prep = PyObject_GetAttrString(meta, "__prepare__");
114 if (prep == NULL) {
115 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
116 PyErr_Clear();
117 ns = PyDict_New();
119 else {
120 Py_DECREF(meta);
121 Py_XDECREF(mkw);
122 Py_DECREF(bases);
123 return NULL;
126 else {
127 PyObject *pargs = PyTuple_Pack(2, name, bases);
128 if (pargs == NULL) {
129 Py_DECREF(prep);
130 Py_DECREF(meta);
131 Py_XDECREF(mkw);
132 Py_DECREF(bases);
133 return NULL;
135 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
136 Py_DECREF(pargs);
137 Py_DECREF(prep);
139 if (ns == NULL) {
140 Py_DECREF(meta);
141 Py_XDECREF(mkw);
142 Py_DECREF(bases);
143 return NULL;
145 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
146 if (cell != NULL) {
147 PyObject *margs;
148 margs = PyTuple_Pack(3, name, bases, ns);
149 if (margs != NULL) {
150 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
151 Py_DECREF(margs);
153 if (cls != NULL && PyCell_Check(cell)) {
154 Py_INCREF(cls);
155 PyCell_SET(cell, cls);
157 Py_DECREF(cell);
159 Py_DECREF(ns);
160 Py_DECREF(meta);
161 Py_XDECREF(mkw);
162 Py_DECREF(bases);
163 return 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.");
171 static PyObject *
172 builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
174 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
175 "level", 0};
176 char *name;
177 PyObject *globals = NULL;
178 PyObject *locals = NULL;
179 PyObject *fromlist = NULL;
180 int level = -1;
182 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
183 kwlist, &name, &globals, &locals, &fromlist, &level))
184 return NULL;
185 return PyImport_ImportModuleLevel(name, globals, locals,
186 fromlist, level);
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.");
204 static PyObject *
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.");
215 static PyObject *
216 builtin_all(PyObject *self, PyObject *v)
218 PyObject *it, *item;
219 PyObject *(*iternext)(PyObject *);
220 int cmp;
222 it = PyObject_GetIter(v);
223 if (it == NULL)
224 return NULL;
225 iternext = *Py_TYPE(it)->tp_iternext;
227 for (;;) {
228 item = iternext(it);
229 if (item == NULL)
230 break;
231 cmp = PyObject_IsTrue(item);
232 Py_DECREF(item);
233 if (cmp < 0) {
234 Py_DECREF(it);
235 return NULL;
237 if (cmp == 0) {
238 Py_DECREF(it);
239 Py_RETURN_FALSE;
242 Py_DECREF(it);
243 if (PyErr_Occurred()) {
244 if (PyErr_ExceptionMatches(PyExc_StopIteration))
245 PyErr_Clear();
246 else
247 return NULL;
249 Py_RETURN_TRUE;
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.");
257 static PyObject *
258 builtin_any(PyObject *self, PyObject *v)
260 PyObject *it, *item;
261 PyObject *(*iternext)(PyObject *);
262 int cmp;
264 it = PyObject_GetIter(v);
265 if (it == NULL)
266 return NULL;
267 iternext = *Py_TYPE(it)->tp_iternext;
269 for (;;) {
270 item = iternext(it);
271 if (item == NULL)
272 break;
273 cmp = PyObject_IsTrue(item);
274 Py_DECREF(item);
275 if (cmp < 0) {
276 Py_DECREF(it);
277 return NULL;
279 if (cmp == 1) {
280 Py_DECREF(it);
281 Py_RETURN_TRUE;
284 Py_DECREF(it);
285 if (PyErr_Occurred()) {
286 if (PyErr_ExceptionMatches(PyExc_StopIteration))
287 PyErr_Clear();
288 else
289 return NULL;
291 Py_RETURN_FALSE;
294 PyDoc_STRVAR(any_doc,
295 "any(iterable) -> bool\n\
297 Return True if bool(x) is True for any x in the iterable.");
299 static PyObject *
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.");
314 static PyObject *
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.");
326 typedef struct {
327 PyObject_HEAD
328 PyObject *func;
329 PyObject *it;
330 } filterobject;
332 static PyObject *
333 filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
335 PyObject *func, *seq;
336 PyObject *it;
337 filterobject *lz;
339 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
340 return NULL;
342 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
343 return NULL;
345 /* Get iterator. */
346 it = PyObject_GetIter(seq);
347 if (it == NULL)
348 return NULL;
350 /* create filterobject structure */
351 lz = (filterobject *)type->tp_alloc(type, 0);
352 if (lz == NULL) {
353 Py_DECREF(it);
354 return NULL;
356 Py_INCREF(func);
357 lz->func = func;
358 lz->it = it;
360 return (PyObject *)lz;
363 static void
364 filter_dealloc(filterobject *lz)
366 PyObject_GC_UnTrack(lz);
367 Py_XDECREF(lz->func);
368 Py_XDECREF(lz->it);
369 Py_TYPE(lz)->tp_free(lz);
372 static int
373 filter_traverse(filterobject *lz, visitproc visit, void *arg)
375 Py_VISIT(lz->it);
376 Py_VISIT(lz->func);
377 return 0;
380 static PyObject *
381 filter_next(filterobject *lz)
383 PyObject *item;
384 PyObject *it = lz->it;
385 long ok;
386 PyObject *(*iternext)(PyObject *);
388 iternext = *Py_TYPE(it)->tp_iternext;
389 for (;;) {
390 item = iternext(it);
391 if (item == NULL)
392 return NULL;
394 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
395 ok = PyObject_IsTrue(item);
396 } else {
397 PyObject *good;
398 good = PyObject_CallFunctionObjArgs(lz->func,
399 item, NULL);
400 if (good == NULL) {
401 Py_DECREF(item);
402 return NULL;
404 ok = PyObject_IsTrue(good);
405 Py_DECREF(good);
407 if (ok)
408 return item;
409 Py_DECREF(item);
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 */
423 0, /* tp_itemsize */
424 /* methods */
425 (destructor)filter_dealloc, /* tp_dealloc */
426 0, /* tp_print */
427 0, /* tp_getattr */
428 0, /* tp_setattr */
429 0, /* tp_reserved */
430 0, /* tp_repr */
431 0, /* tp_as_number */
432 0, /* tp_as_sequence */
433 0, /* tp_as_mapping */
434 0, /* tp_hash */
435 0, /* tp_call */
436 0, /* tp_str */
437 PyObject_GenericGetAttr, /* tp_getattro */
438 0, /* tp_setattro */
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 */
444 0, /* tp_clear */
445 0, /* tp_richcompare */
446 0, /* tp_weaklistoffset */
447 PyObject_SelfIter, /* tp_iter */
448 (iternextfunc)filter_next, /* tp_iternext */
449 0, /* tp_methods */
450 0, /* tp_members */
451 0, /* tp_getset */
452 0, /* tp_base */
453 0, /* tp_dict */
454 0, /* tp_descr_get */
455 0, /* tp_descr_set */
456 0, /* tp_dictoffset */
457 0, /* tp_init */
458 PyType_GenericAlloc, /* tp_alloc */
459 filter_new, /* tp_new */
460 PyObject_GC_Del, /* tp_free */
464 static PyObject *
465 builtin_format(PyObject *self, PyObject *args)
467 PyObject *value;
468 PyObject *format_spec = NULL;
470 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
471 return NULL;
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 \"\"");
482 static PyObject *
483 builtin_chr(PyObject *self, PyObject *args)
485 int x;
487 if (!PyArg_ParseTuple(args, "i:chr", &x))
488 return NULL;
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
499 PyDoc_STR(
500 "\nIf 0x10000 <= i, a surrogate pair is returned."
502 #endif
506 static char *
507 source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
509 char *str;
510 Py_ssize_t size;
512 if (PyUnicode_Check(cmd)) {
513 cf->cf_flags |= PyCF_IGNORE_COOKIE;
514 cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
515 if (cmd == NULL)
516 return NULL;
518 else if (!PyObject_CheckReadBuffer(cmd)) {
519 PyErr_Format(PyExc_TypeError,
520 "%s() arg 1 must be a %s object",
521 funcname, what);
522 return NULL;
524 if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
525 return NULL;
527 if (strlen(str) != size) {
528 PyErr_SetString(PyExc_TypeError,
529 "source code string cannot contain null bytes");
530 return NULL;
532 return str;
535 static PyObject *
536 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
538 char *str;
539 char *filename;
540 char *startstr;
541 int mode = -1;
542 int dont_inherit = 0;
543 int supplied_flags = 0;
544 int is_ast;
545 PyCompilerFlags cf;
546 PyObject *cmd;
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))
554 return NULL;
556 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
558 if (supplied_flags &
559 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
561 PyErr_SetString(PyExc_ValueError,
562 "compile(): unrecognised flags");
563 return NULL;
565 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
567 if (!dont_inherit) {
568 PyEval_MergeCompilerFlags(&cf);
571 if (strcmp(startstr, "exec") == 0)
572 mode = 0;
573 else if (strcmp(startstr, "eval") == 0)
574 mode = 1;
575 else if (strcmp(startstr, "single") == 0)
576 mode = 2;
577 else {
578 PyErr_SetString(PyExc_ValueError,
579 "compile() arg 3 must be 'exec', 'eval' or 'single'");
580 return NULL;
583 is_ast = PyAST_Check(cmd);
584 if (is_ast == -1)
585 return NULL;
586 if (is_ast) {
587 PyObject *result;
588 if (supplied_flags & PyCF_ONLY_AST) {
589 Py_INCREF(cmd);
590 result = cmd;
592 else {
593 PyArena *arena;
594 mod_ty mod;
596 arena = PyArena_New();
597 mod = PyAST_obj2mod(cmd, arena, mode);
598 if (mod == NULL) {
599 PyArena_Free(arena);
600 return NULL;
602 result = (PyObject*)PyAST_Compile(mod, filename,
603 &cf, arena);
604 PyArena_Free(arena);
606 return result;
609 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
610 if (str == NULL)
611 return NULL;
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.");
631 static PyObject *
632 builtin_dir(PyObject *self, PyObject *args)
634 PyObject *arg = NULL;
636 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
637 return NULL;
638 return PyObject_Dir(arg);
641 PyDoc_STRVAR(dir_doc,
642 "dir([object]) -> list of strings\n"
643 "\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"
651 " of its bases.\n"
652 " for any other object: its attributes, its class's attributes, and\n"
653 " recursively the attributes of its class's base classes.");
655 static PyObject *
656 builtin_divmod(PyObject *self, PyObject *args)
658 PyObject *v, *w;
660 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
661 return NULL;
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.");
671 static PyObject *
672 builtin_eval(PyObject *self, PyObject *args)
674 PyObject *cmd, *result, *tmp = NULL;
675 PyObject *globals = Py_None, *locals = Py_None;
676 char *str;
677 PyCompilerFlags cf;
679 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
680 return NULL;
681 if (locals != Py_None && !PyMapping_Check(locals)) {
682 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
683 return NULL;
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");
689 return NULL;
691 if (globals == Py_None) {
692 globals = PyEval_GetGlobals();
693 if (locals == Py_None)
694 locals = PyEval_GetLocals();
696 else if (locals == Py_None)
697 locals = globals;
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");
703 return NULL;
706 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
707 if (PyDict_SetItemString(globals, "__builtins__",
708 PyEval_GetBuiltins()) != 0)
709 return NULL;
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");
716 return NULL;
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);
723 if (str == NULL)
724 return NULL;
726 while (*str == ' ' || *str == '\t')
727 str++;
729 (void)PyEval_MergeCompilerFlags(&cf);
730 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
731 Py_XDECREF(tmp);
732 return result;
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");
745 static PyObject *
746 builtin_exec(PyObject *self, PyObject *args)
748 PyObject *v;
749 PyObject *prog, *globals = Py_None, *locals = Py_None;
750 int plain = 0;
752 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
753 return NULL;
755 if (globals == Py_None) {
756 globals = PyEval_GetGlobals();
757 if (locals == Py_None) {
758 locals = PyEval_GetLocals();
759 plain = 1;
761 if (!globals || !locals) {
762 PyErr_SetString(PyExc_SystemError,
763 "globals and locals cannot be NULL");
764 return NULL;
767 else if (locals == Py_None)
768 locals = globals;
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);
773 return NULL;
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);
779 return NULL;
781 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
782 if (PyDict_SetItemString(globals, "__builtins__",
783 PyEval_GetBuiltins()) != 0)
784 return NULL;
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");
792 return NULL;
794 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
796 else {
797 char *str;
798 PyCompilerFlags cf;
799 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
800 str = source_as_string(prog, "exec",
801 "string, bytes or code", &cf);
802 if (str == NULL)
803 return NULL;
804 if (PyEval_MergeCompilerFlags(&cf))
805 v = PyRun_StringFlags(str, Py_file_input, globals,
806 locals, &cf);
807 else
808 v = PyRun_String(str, Py_file_input, globals, locals);
810 if (v == NULL)
811 return NULL;
812 Py_DECREF(v);
813 Py_RETURN_NONE;
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\
820 object.\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.");
825 static PyObject *
826 builtin_getattr(PyObject *self, PyObject *args)
828 PyObject *v, *result, *dflt = NULL;
829 PyObject *name;
831 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
832 return NULL;
834 if (!PyUnicode_Check(name)) {
835 PyErr_SetString(PyExc_TypeError,
836 "getattr(): attribute name must be string");
837 return NULL;
839 result = PyObject_GetAttr(v, name);
840 if (result == NULL && dflt != NULL &&
841 PyErr_ExceptionMatches(PyExc_AttributeError))
843 PyErr_Clear();
844 Py_INCREF(dflt);
845 result = dflt;
847 return result;
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.");
858 static PyObject *
859 builtin_globals(PyObject *self)
861 PyObject *d;
863 d = PyEval_GetGlobals();
864 Py_XINCREF(d);
865 return d;
868 PyDoc_STRVAR(globals_doc,
869 "globals() -> dictionary\n\
871 Return the dictionary containing the current scope's global variables.");
874 static PyObject *
875 builtin_hasattr(PyObject *self, PyObject *args)
877 PyObject *v;
878 PyObject *name;
880 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
881 return NULL;
882 if (!PyUnicode_Check(name)) {
883 PyErr_SetString(PyExc_TypeError,
884 "hasattr(): attribute name must be string");
885 return NULL;
887 v = PyObject_GetAttr(v, name);
888 if (v == NULL) {
889 if (!PyErr_ExceptionMatches(PyExc_Exception))
890 return NULL;
891 else {
892 PyErr_Clear();
893 Py_INCREF(Py_False);
894 return Py_False;
897 Py_DECREF(v);
898 Py_INCREF(Py_True);
899 return Py_True;
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.)");
909 static PyObject *
910 builtin_id(PyObject *self, PyObject *v)
912 return PyLong_FromVoidPtr(v);
915 PyDoc_STRVAR(id_doc,
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 ************************************************************/
924 typedef struct {
925 PyObject_HEAD
926 PyObject *iters;
927 PyObject *func;
928 } mapobject;
930 static PyObject *
931 map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
933 PyObject *it, *iters, *func;
934 mapobject *lz;
935 Py_ssize_t numargs, i;
937 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
938 return NULL;
940 numargs = PyTuple_Size(args);
941 if (numargs < 2) {
942 PyErr_SetString(PyExc_TypeError,
943 "map() must have at least two arguments.");
944 return NULL;
947 iters = PyTuple_New(numargs-1);
948 if (iters == NULL)
949 return NULL;
951 for (i=1 ; i<numargs ; i++) {
952 /* Get iterator. */
953 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
954 if (it == NULL) {
955 Py_DECREF(iters);
956 return NULL;
958 PyTuple_SET_ITEM(iters, i-1, it);
961 /* create mapobject structure */
962 lz = (mapobject *)type->tp_alloc(type, 0);
963 if (lz == NULL) {
964 Py_DECREF(iters);
965 return NULL;
967 lz->iters = iters;
968 func = PyTuple_GET_ITEM(args, 0);
969 Py_INCREF(func);
970 lz->func = func;
972 return (PyObject *)lz;
975 static void
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);
984 static int
985 map_traverse(mapobject *lz, visitproc visit, void *arg)
987 Py_VISIT(lz->iters);
988 Py_VISIT(lz->func);
989 return 0;
992 static PyObject *
993 map_next(mapobject *lz)
995 PyObject *val;
996 PyObject *argtuple;
997 PyObject *result;
998 Py_ssize_t numargs, i;
1000 numargs = PyTuple_Size(lz->iters);
1001 argtuple = PyTuple_New(numargs);
1002 if (argtuple == NULL)
1003 return NULL;
1005 for (i=0 ; i<numargs ; i++) {
1006 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1007 if (val == NULL) {
1008 Py_DECREF(argtuple);
1009 return NULL;
1011 PyTuple_SET_ITEM(argtuple, i, val);
1013 result = PyObject_Call(lz->func, argtuple, NULL);
1014 Py_DECREF(argtuple);
1015 return result;
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 */
1029 /* methods */
1030 (destructor)map_dealloc, /* tp_dealloc */
1031 0, /* tp_print */
1032 0, /* tp_getattr */
1033 0, /* tp_setattr */
1034 0, /* tp_reserved */
1035 0, /* tp_repr */
1036 0, /* tp_as_number */
1037 0, /* tp_as_sequence */
1038 0, /* tp_as_mapping */
1039 0, /* tp_hash */
1040 0, /* tp_call */
1041 0, /* tp_str */
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 */
1049 0, /* tp_clear */
1050 0, /* tp_richcompare */
1051 0, /* tp_weaklistoffset */
1052 PyObject_SelfIter, /* tp_iter */
1053 (iternextfunc)map_next, /* tp_iternext */
1054 0, /* tp_methods */
1055 0, /* tp_members */
1056 0, /* tp_getset */
1057 0, /* tp_base */
1058 0, /* tp_dict */
1059 0, /* tp_descr_get */
1060 0, /* tp_descr_set */
1061 0, /* tp_dictoffset */
1062 0, /* tp_init */
1063 PyType_GenericAlloc, /* tp_alloc */
1064 map_new, /* tp_new */
1065 PyObject_GC_Del, /* tp_free */
1068 static PyObject *
1069 builtin_next(PyObject *self, PyObject *args)
1071 PyObject *it, *res;
1072 PyObject *def = NULL;
1074 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1075 return NULL;
1076 if (!PyIter_Check(it)) {
1077 PyErr_Format(PyExc_TypeError,
1078 "%.200s object is not an iterator",
1079 it->ob_type->tp_name);
1080 return NULL;
1083 res = (*it->ob_type->tp_iternext)(it);
1084 if (res != NULL) {
1085 return res;
1086 } else if (def != NULL) {
1087 if (PyErr_Occurred()) {
1088 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1089 return NULL;
1090 PyErr_Clear();
1092 Py_INCREF(def);
1093 return def;
1094 } else if (PyErr_Occurred()) {
1095 return NULL;
1096 } else {
1097 PyErr_SetNone(PyExc_StopIteration);
1098 return NULL;
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.");
1109 static PyObject *
1110 builtin_setattr(PyObject *self, PyObject *args)
1112 PyObject *v;
1113 PyObject *name;
1114 PyObject *value;
1116 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1117 return NULL;
1118 if (PyObject_SetAttr(v, name, value) != 0)
1119 return NULL;
1120 Py_INCREF(Py_None);
1121 return Py_None;
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\
1128 ``x.y = v''.");
1131 static PyObject *
1132 builtin_delattr(PyObject *self, PyObject *args)
1134 PyObject *v;
1135 PyObject *name;
1137 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1138 return NULL;
1139 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1140 return NULL;
1141 Py_INCREF(Py_None);
1142 return Py_None;
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\
1149 ``del x.y''.");
1152 static PyObject *
1153 builtin_hash(PyObject *self, PyObject *v)
1155 long x;
1157 x = PyObject_Hash(v);
1158 if (x == -1)
1159 return NULL;
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.");
1170 static PyObject *
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.");
1182 static PyObject *
1183 builtin_iter(PyObject *self, PyObject *args)
1185 PyObject *v, *w = NULL;
1187 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1188 return NULL;
1189 if (w == NULL)
1190 return PyObject_GetIter(v);
1191 if (!PyCallable_Check(v)) {
1192 PyErr_SetString(PyExc_TypeError,
1193 "iter(v, w): v must be callable");
1194 return NULL;
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.");
1208 static PyObject *
1209 builtin_len(PyObject *self, PyObject *v)
1211 Py_ssize_t res;
1213 res = PyObject_Size(v);
1214 if (res < 0 && PyErr_Occurred())
1215 return NULL;
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.");
1225 static PyObject *
1226 builtin_locals(PyObject *self)
1228 PyObject *d;
1230 d = PyEval_GetLocals();
1231 Py_XINCREF(d);
1232 return d;
1235 PyDoc_STRVAR(locals_doc,
1236 "locals() -> dictionary\n\
1238 Update and return a dictionary containing the current scope's local variables.");
1241 static PyObject *
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)
1248 v = args;
1249 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1250 return NULL;
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);
1257 return NULL;
1259 Py_INCREF(keyfunc);
1262 it = PyObject_GetIter(v);
1263 if (it == NULL) {
1264 Py_XDECREF(keyfunc);
1265 return NULL;
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);
1274 if (val == NULL)
1275 goto Fail_it_item;
1277 /* no key function; the value is the item */
1278 else {
1279 val = item;
1280 Py_INCREF(val);
1283 /* maximum value and item are unset; set them */
1284 if (maxval == NULL) {
1285 maxitem = item;
1286 maxval = val;
1288 /* maximum value and item are set; update them as necessary */
1289 else {
1290 int cmp = PyObject_RichCompareBool(val, maxval, op);
1291 if (cmp < 0)
1292 goto Fail_it_item_and_val;
1293 else if (cmp > 0) {
1294 Py_DECREF(maxval);
1295 Py_DECREF(maxitem);
1296 maxval = val;
1297 maxitem = item;
1299 else {
1300 Py_DECREF(item);
1301 Py_DECREF(val);
1305 if (PyErr_Occurred())
1306 goto Fail_it;
1307 if (maxval == NULL) {
1308 PyErr_Format(PyExc_ValueError,
1309 "%s() arg is an empty sequence", name);
1310 assert(maxitem == NULL);
1312 else
1313 Py_DECREF(maxval);
1314 Py_DECREF(it);
1315 Py_XDECREF(keyfunc);
1316 return maxitem;
1318 Fail_it_item_and_val:
1319 Py_DECREF(val);
1320 Fail_it_item:
1321 Py_DECREF(item);
1322 Fail_it:
1323 Py_XDECREF(maxval);
1324 Py_XDECREF(maxitem);
1325 Py_DECREF(it);
1326 Py_XDECREF(keyfunc);
1327 return NULL;
1330 static PyObject *
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.");
1344 static PyObject *
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.");
1358 static PyObject *
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.");
1370 static PyObject *
1371 builtin_ord(PyObject *self, PyObject* obj)
1373 long ord;
1374 Py_ssize_t size;
1376 if (PyBytes_Check(obj)) {
1377 size = PyBytes_GET_SIZE(obj);
1378 if (size == 1) {
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);
1385 if (size == 1) {
1386 ord = (long)*PyUnicode_AS_UNICODE(obj);
1387 return PyLong_FromLong(ord);
1389 #ifndef Py_UNICODE_WIDE
1390 if (size == 2) {
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)) +
1397 0x00010000);
1398 return PyLong_FromLong(ord);
1401 #endif
1403 else if (PyByteArray_Check(obj)) {
1404 /* XXX Hopefully this is temporary */
1405 size = PyByteArray_GET_SIZE(obj);
1406 if (size == 1) {
1407 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1408 return PyLong_FromLong(ord);
1411 else {
1412 PyErr_Format(PyExc_TypeError,
1413 "ord() expected string of length 1, but " \
1414 "%.200s found", obj->ob_type->tp_name);
1415 return NULL;
1418 PyErr_Format(PyExc_TypeError,
1419 "ord() expected a character, "
1420 "but string of length %zd found",
1421 size);
1422 return NULL;
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
1431 PyDoc_STR(
1432 "\nA valid surrogate pair is also accepted."
1434 #endif
1438 static PyObject *
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))
1444 return NULL;
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).");
1456 static PyObject *
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;
1462 int i, err;
1464 if (dummy_args == NULL) {
1465 if (!(dummy_args = PyTuple_New(0)))
1466 return NULL;
1468 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1469 kwlist, &sep, &end, &file))
1470 return NULL;
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)
1475 Py_RETURN_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);
1482 return NULL;
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);
1488 return NULL;
1491 for (i = 0; i < PyTuple_Size(args); i++) {
1492 if (i > 0) {
1493 if (sep == NULL || sep == Py_None)
1494 err = PyFile_WriteString(" ", file);
1495 else
1496 err = PyFile_WriteObject(sep, file,
1497 Py_PRINT_RAW);
1498 if (err)
1499 return NULL;
1501 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1502 Py_PRINT_RAW);
1503 if (err)
1504 return NULL;
1507 if (end == NULL || end == Py_None)
1508 err = PyFile_WriteString("\n", file);
1509 else
1510 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1511 if (err)
1512 return NULL;
1514 Py_RETURN_NONE;
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.");
1527 static PyObject *
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");
1534 PyObject *tmp;
1535 long fd;
1536 int tty;
1538 /* Parse arguments */
1539 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1540 return NULL;
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");
1546 return NULL;
1548 if (fout == NULL || fout == Py_None) {
1549 PyErr_SetString(PyExc_RuntimeError,
1550 "input(): lost sys.stdout");
1551 return NULL;
1553 if (ferr == NULL || ferr == Py_None) {
1554 PyErr_SetString(PyExc_RuntimeError,
1555 "input(): lost sys.stderr");
1556 return NULL;
1559 /* First of all, flush stderr */
1560 tmp = PyObject_CallMethod(ferr, "flush", "");
1561 if (tmp == NULL)
1562 PyErr_Clear();
1563 else
1564 Py_DECREF(tmp);
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", "");
1570 if (tmp == NULL) {
1571 PyErr_Clear();
1572 tty = 0;
1574 else {
1575 fd = PyLong_AsLong(tmp);
1576 Py_DECREF(tmp);
1577 if (fd < 0 && PyErr_Occurred())
1578 return NULL;
1579 tty = fd == fileno(stdin) && isatty(fd);
1581 if (tty) {
1582 tmp = PyObject_CallMethod(fout, "fileno", "");
1583 if (tmp == NULL)
1584 PyErr_Clear();
1585 else {
1586 fd = PyLong_AsLong(tmp);
1587 Py_DECREF(tmp);
1588 if (fd < 0 && PyErr_Occurred())
1589 return NULL;
1590 tty = fd == fileno(stdout) && isatty(fd);
1594 /* If we're interactive, use (GNU) readline */
1595 if (tty) {
1596 PyObject *po;
1597 char *prompt;
1598 char *s;
1599 PyObject *stdin_encoding;
1600 PyObject *result;
1602 stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1603 if (!stdin_encoding)
1604 /* stdin is a text stream, so it must have an
1605 encoding. */
1606 return NULL;
1607 tmp = PyObject_CallMethod(fout, "flush", "");
1608 if (tmp == NULL)
1609 PyErr_Clear();
1610 else
1611 Py_DECREF(tmp);
1612 if (promptarg != NULL) {
1613 PyObject *stringpo;
1614 PyObject *stdout_encoding;
1615 stdout_encoding = PyObject_GetAttrString(fout,
1616 "encoding");
1617 if (stdout_encoding == NULL) {
1618 Py_DECREF(stdin_encoding);
1619 return NULL;
1621 stringpo = PyObject_Str(promptarg);
1622 if (stringpo == NULL) {
1623 Py_DECREF(stdin_encoding);
1624 Py_DECREF(stdout_encoding);
1625 return NULL;
1627 po = PyUnicode_AsEncodedString(stringpo,
1628 _PyUnicode_AsString(stdout_encoding), NULL);
1629 Py_DECREF(stdout_encoding);
1630 Py_DECREF(stringpo);
1631 if (po == NULL) {
1632 Py_DECREF(stdin_encoding);
1633 return NULL;
1635 prompt = PyBytes_AsString(po);
1636 if (prompt == NULL) {
1637 Py_DECREF(stdin_encoding);
1638 Py_DECREF(po);
1639 return NULL;
1642 else {
1643 po = NULL;
1644 prompt = "";
1646 s = PyOS_Readline(stdin, stdout, prompt);
1647 Py_XDECREF(po);
1648 if (s == NULL) {
1649 if (!PyErr_Occurred())
1650 PyErr_SetNone(PyExc_KeyboardInterrupt);
1651 Py_DECREF(stdin_encoding);
1652 return NULL;
1654 if (*s == '\0') {
1655 PyErr_SetNone(PyExc_EOFError);
1656 result = NULL;
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");
1663 result = NULL;
1665 else {
1666 result = PyUnicode_Decode
1667 (s, len-1,
1668 _PyUnicode_AsString(stdin_encoding),
1669 NULL);
1672 Py_DECREF(stdin_encoding);
1673 PyMem_FREE(s);
1674 return result;
1677 /* Fallback if we're not interactive */
1678 if (promptarg != NULL) {
1679 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1680 return NULL;
1682 tmp = PyObject_CallMethod(fout, "flush", "");
1683 if (tmp == NULL)
1684 PyErr_Clear();
1685 else
1686 Py_DECREF(tmp);
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.");
1699 static PyObject *
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.");
1712 static PyObject *
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))
1722 return NULL;
1724 if (Py_TYPE(number)->tp_dict == NULL) {
1725 if (PyType_Ready(Py_TYPE(number)) < 0)
1726 return NULL;
1729 if (round_str == NULL) {
1730 round_str = PyUnicode_InternFromString("__round__");
1731 if (round_str == NULL)
1732 return 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);
1740 return NULL;
1743 if (ndigits == NULL)
1744 return PyObject_CallFunction(round, "O", number);
1745 else
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.");
1757 static PyObject *
1758 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1760 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1761 PyObject *callable;
1762 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1763 int reverse;
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))
1768 return NULL;
1770 newlist = PySequence_List(seq);
1771 if (newlist == NULL)
1772 return NULL;
1774 callable = PyObject_GetAttrString(newlist, "sort");
1775 if (callable == NULL) {
1776 Py_DECREF(newlist);
1777 return NULL;
1780 newargs = PyTuple_GetSlice(args, 1, 4);
1781 if (newargs == NULL) {
1782 Py_DECREF(newlist);
1783 Py_DECREF(callable);
1784 return NULL;
1787 v = PyObject_Call(callable, newargs, kwds);
1788 Py_DECREF(newargs);
1789 Py_DECREF(callable);
1790 if (v == NULL) {
1791 Py_DECREF(newlist);
1792 return NULL;
1794 Py_DECREF(v);
1795 return newlist;
1798 PyDoc_STRVAR(sorted_doc,
1799 "sorted(iterable, key=None, reverse=False) --> new sorted list");
1801 static PyObject *
1802 builtin_vars(PyObject *self, PyObject *args)
1804 PyObject *v = NULL;
1805 PyObject *d;
1807 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1808 return NULL;
1809 if (v == NULL) {
1810 d = PyEval_GetLocals();
1811 if (d == NULL) {
1812 if (!PyErr_Occurred())
1813 PyErr_SetString(PyExc_SystemError,
1814 "vars(): no locals!?");
1816 else
1817 Py_INCREF(d);
1819 else {
1820 d = PyObject_GetAttrString(v, "__dict__");
1821 if (d == NULL) {
1822 PyErr_SetString(PyExc_TypeError,
1823 "vars() argument must have __dict__ attribute");
1824 return NULL;
1827 return d;
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__.");
1836 static PyObject*
1837 builtin_sum(PyObject *self, PyObject *args)
1839 PyObject *seq;
1840 PyObject *result = NULL;
1841 PyObject *temp, *item, *iter;
1843 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1844 return NULL;
1846 iter = PyObject_GetIter(seq);
1847 if (iter == NULL)
1848 return NULL;
1850 if (result == NULL) {
1851 result = PyLong_FromLong(0);
1852 if (result == NULL) {
1853 Py_DECREF(iter);
1854 return NULL;
1856 } else {
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]");
1861 Py_DECREF(iter);
1862 return NULL;
1864 if (PyByteArray_Check(result)) {
1865 PyErr_SetString(PyExc_TypeError,
1866 "sum() can't sum bytes [use b''.join(seq) instead]");
1867 Py_DECREF(iter);
1868 return NULL;
1871 Py_INCREF(result);
1874 #ifndef SLOW_SUM
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)) {
1880 int overflow;
1881 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1882 /* If this already overflowed, don't even enter the loop. */
1883 if (overflow == 0) {
1884 Py_DECREF(result);
1885 result = NULL;
1887 while(result == NULL) {
1888 item = PyIter_Next(iter);
1889 if (item == NULL) {
1890 Py_DECREF(iter);
1891 if (PyErr_Occurred())
1892 return NULL;
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)) {
1899 i_result = x;
1900 Py_DECREF(item);
1901 continue;
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);
1907 Py_DECREF(result);
1908 Py_DECREF(item);
1909 result = temp;
1910 if (result == NULL) {
1911 Py_DECREF(iter);
1912 return NULL;
1917 if (PyFloat_CheckExact(result)) {
1918 double f_result = PyFloat_AS_DOUBLE(result);
1919 Py_DECREF(result);
1920 result = NULL;
1921 while(result == NULL) {
1922 item = PyIter_Next(iter);
1923 if (item == NULL) {
1924 Py_DECREF(iter);
1925 if (PyErr_Occurred())
1926 return NULL;
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)
1933 Py_DECREF(item);
1934 continue;
1936 if (PyLong_CheckExact(item)) {
1937 long value;
1938 int overflow;
1939 value = PyLong_AsLongAndOverflow(item, &overflow);
1940 if (!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)
1944 Py_DECREF(item);
1945 continue;
1948 result = PyFloat_FromDouble(f_result);
1949 temp = PyNumber_Add(result, item);
1950 Py_DECREF(result);
1951 Py_DECREF(item);
1952 result = temp;
1953 if (result == NULL) {
1954 Py_DECREF(iter);
1955 return NULL;
1959 #endif
1961 for(;;) {
1962 item = PyIter_Next(iter);
1963 if (item == NULL) {
1964 /* error, or end-of-sequence */
1965 if (PyErr_Occurred()) {
1966 Py_DECREF(result);
1967 result = NULL;
1969 break;
1971 temp = PyNumber_Add(result, item);
1972 Py_DECREF(result);
1973 Py_DECREF(item);
1974 result = temp;
1975 if (result == NULL)
1976 break;
1978 Py_DECREF(iter);
1979 return result;
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.");
1990 static PyObject *
1991 builtin_isinstance(PyObject *self, PyObject *args)
1993 PyObject *inst;
1994 PyObject *cls;
1995 int retval;
1997 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
1998 return NULL;
2000 retval = PyObject_IsInstance(inst, cls);
2001 if (retval < 0)
2002 return NULL;
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.).");
2015 static PyObject *
2016 builtin_issubclass(PyObject *self, PyObject *args)
2018 PyObject *derived;
2019 PyObject *cls;
2020 int retval;
2022 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2023 return NULL;
2025 retval = PyObject_IsSubclass(derived, cls);
2026 if (retval < 0)
2027 return NULL;
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.).");
2039 typedef struct {
2040 PyObject_HEAD
2041 Py_ssize_t tuplesize;
2042 PyObject *ittuple; /* tuple of iterators */
2043 PyObject *result;
2044 } zipobject;
2046 static PyObject *
2047 zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2049 zipobject *lz;
2050 Py_ssize_t i;
2051 PyObject *ittuple; /* tuple of iterators */
2052 PyObject *result;
2053 Py_ssize_t tuplesize = PySequence_Length(args);
2055 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2056 return NULL;
2058 /* args must be a tuple */
2059 assert(PyTuple_Check(args));
2061 /* obtain iterators */
2062 ittuple = PyTuple_New(tuplesize);
2063 if (ittuple == NULL)
2064 return NULL;
2065 for (i=0; i < tuplesize; ++i) {
2066 PyObject *item = PyTuple_GET_ITEM(args, i);
2067 PyObject *it = PyObject_GetIter(item);
2068 if (it == NULL) {
2069 if (PyErr_ExceptionMatches(PyExc_TypeError))
2070 PyErr_Format(PyExc_TypeError,
2071 "zip argument #%zd must support iteration",
2072 i+1);
2073 Py_DECREF(ittuple);
2074 return NULL;
2076 PyTuple_SET_ITEM(ittuple, i, it);
2079 /* create a result holder */
2080 result = PyTuple_New(tuplesize);
2081 if (result == NULL) {
2082 Py_DECREF(ittuple);
2083 return NULL;
2085 for (i=0 ; i < tuplesize ; i++) {
2086 Py_INCREF(Py_None);
2087 PyTuple_SET_ITEM(result, i, Py_None);
2090 /* create zipobject structure */
2091 lz = (zipobject *)type->tp_alloc(type, 0);
2092 if (lz == NULL) {
2093 Py_DECREF(ittuple);
2094 Py_DECREF(result);
2095 return NULL;
2097 lz->ittuple = ittuple;
2098 lz->tuplesize = tuplesize;
2099 lz->result = result;
2101 return (PyObject *)lz;
2104 static void
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);
2113 static int
2114 zip_traverse(zipobject *lz, visitproc visit, void *arg)
2116 Py_VISIT(lz->ittuple);
2117 Py_VISIT(lz->result);
2118 return 0;
2121 static PyObject *
2122 zip_next(zipobject *lz)
2124 Py_ssize_t i;
2125 Py_ssize_t tuplesize = lz->tuplesize;
2126 PyObject *result = lz->result;
2127 PyObject *it;
2128 PyObject *item;
2129 PyObject *olditem;
2131 if (tuplesize == 0)
2132 return NULL;
2133 if (Py_REFCNT(result) == 1) {
2134 Py_INCREF(result);
2135 for (i=0 ; i < tuplesize ; i++) {
2136 it = PyTuple_GET_ITEM(lz->ittuple, i);
2137 item = (*Py_TYPE(it)->tp_iternext)(it);
2138 if (item == NULL) {
2139 Py_DECREF(result);
2140 return NULL;
2142 olditem = PyTuple_GET_ITEM(result, i);
2143 PyTuple_SET_ITEM(result, i, item);
2144 Py_DECREF(olditem);
2146 } else {
2147 result = PyTuple_New(tuplesize);
2148 if (result == NULL)
2149 return NULL;
2150 for (i=0 ; i < tuplesize ; i++) {
2151 it = PyTuple_GET_ITEM(lz->ittuple, i);
2152 item = (*Py_TYPE(it)->tp_iternext)(it);
2153 if (item == NULL) {
2154 Py_DECREF(result);
2155 return NULL;
2157 PyTuple_SET_ITEM(result, i, item);
2160 return result;
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 */
2176 /* methods */
2177 (destructor)zip_dealloc, /* tp_dealloc */
2178 0, /* tp_print */
2179 0, /* tp_getattr */
2180 0, /* tp_setattr */
2181 0, /* tp_reserved */
2182 0, /* tp_repr */
2183 0, /* tp_as_number */
2184 0, /* tp_as_sequence */
2185 0, /* tp_as_mapping */
2186 0, /* tp_hash */
2187 0, /* tp_call */
2188 0, /* tp_str */
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 */
2196 0, /* tp_clear */
2197 0, /* tp_richcompare */
2198 0, /* tp_weaklistoffset */
2199 PyObject_SelfIter, /* tp_iter */
2200 (iternextfunc)zip_next, /* tp_iternext */
2201 0, /* tp_methods */
2202 0, /* tp_members */
2203 0, /* tp_getset */
2204 0, /* tp_base */
2205 0, /* tp_dict */
2206 0, /* tp_descr_get */
2207 0, /* tp_descr_set */
2208 0, /* tp_dictoffset */
2209 0, /* tp_init */
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},
2258 {NULL, NULL},
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,
2268 "builtins",
2269 builtin_doc,
2270 -1, /* multiple "initialization" just copies the module dict. */
2271 builtin_methods,
2272 NULL,
2273 NULL,
2274 NULL,
2275 NULL
2279 PyObject *
2280 _PyBuiltin_Init(void)
2282 PyObject *mod, *dict, *debug;
2283 mod = PyModule_Create(&builtinsmodule);
2284 if (mod == NULL)
2285 return NULL;
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)
2296 #else
2297 #define ADD_TO_ALL(OBJECT) (void)0
2298 #endif
2300 #define SETBUILTIN(NAME, OBJECT) \
2301 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2302 return NULL; \
2303 ADD_TO_ALL(OBJECT)
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);
2317 #endif
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) {
2340 Py_XDECREF(debug);
2341 return NULL;
2343 Py_XDECREF(debug);
2345 return mod;
2346 #undef ADD_TO_ALL
2347 #undef SETBUILTIN