comparison cos/python/Python/bltinmodule.c @ 27:7f74363f4c82

Added some files for the python port
author windel
date Tue, 27 Dec 2011 18:59:02 +0100
parents
children
comparison
equal deleted inserted replaced
26:dcce92b1efbc 27:7f74363f4c82
1 /* Built-in functions */
2
3 #include "Python.h"
4 #include "Python-ast.h"
5
6 #include "node.h"
7 #include "code.h"
8
9 #include "asdl.h"
10 #include "ast.h"
11
12 #include <ctype.h>
13
14 #ifdef HAVE_LANGINFO_H
15 #include <langinfo.h> /* CODESET */
16 #endif
17
18 /* The default encoding used by the platform file system APIs
19 Can remain NULL for all platforms that don't have such a concept
20
21 Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
22 values for Py_FileSystemDefaultEncoding!
23 */
24 #ifdef HAVE_MBCS
25 const char *Py_FileSystemDefaultEncoding = "mbcs";
26 int Py_HasFileSystemDefaultEncoding = 1;
27 #elif defined(__APPLE__)
28 const char *Py_FileSystemDefaultEncoding = "utf-8";
29 int Py_HasFileSystemDefaultEncoding = 1;
30 #else
31 const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
32 int Py_HasFileSystemDefaultEncoding = 0;
33 #endif
34
35 _Py_IDENTIFIER(fileno);
36 _Py_IDENTIFIER(flush);
37
38 static PyObject *
39 builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40 {
41 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
42 PyObject *cls = NULL;
43 Py_ssize_t nargs;
44 int isclass;
45 _Py_IDENTIFIER(__prepare__);
46
47 assert(args != NULL);
48 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple");
51 return NULL;
52 }
53 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments");
57 return NULL;
58 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
60 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string");
64 return NULL;
65 }
66 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL)
68 return NULL;
69
70 if (kwds == NULL) {
71 meta = NULL;
72 mkw = NULL;
73 }
74 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) {
77 Py_DECREF(bases);
78 return NULL;
79 }
80 meta = PyDict_GetItemString(mkw, "metaclass");
81 if (meta != NULL) {
82 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
84 Py_DECREF(meta);
85 Py_DECREF(mkw);
86 Py_DECREF(bases);
87 return NULL;
88 }
89 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta);
91 }
92 }
93 if (meta == NULL) {
94 /* if there are no bases, use type: */
95 if (PyTuple_GET_SIZE(bases) == 0) {
96 meta = (PyObject *) (&PyType_Type);
97 }
98 /* else get the type of the first base */
99 else {
100 PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
101 meta = (PyObject *) (base0->ob_type);
102 }
103 Py_INCREF(meta);
104 isclass = 1; /* meta is really a class */
105 }
106
107 if (isclass) {
108 /* meta is really a class, so check for a more derived
109 metaclass, or possible metaclass conflicts: */
110 winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta,
111 bases);
112 if (winner == NULL) {
113 Py_DECREF(meta);
114 Py_XDECREF(mkw);
115 Py_DECREF(bases);
116 return NULL;
117 }
118 if (winner != meta) {
119 Py_DECREF(meta);
120 meta = winner;
121 Py_INCREF(meta);
122 }
123 }
124 /* else: meta is not a class, so we cannot do the metaclass
125 calculation, so we will use the explicitly given object as it is */
126 prep = _PyObject_GetAttrId(meta, &PyId___prepare__);
127 if (prep == NULL) {
128 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
129 PyErr_Clear();
130 ns = PyDict_New();
131 }
132 else {
133 Py_DECREF(meta);
134 Py_XDECREF(mkw);
135 Py_DECREF(bases);
136 return NULL;
137 }
138 }
139 else {
140 PyObject *pargs = PyTuple_Pack(2, name, bases);
141 if (pargs == NULL) {
142 Py_DECREF(prep);
143 Py_DECREF(meta);
144 Py_XDECREF(mkw);
145 Py_DECREF(bases);
146 return NULL;
147 }
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs);
150 Py_DECREF(prep);
151 }
152 if (ns == NULL) {
153 Py_DECREF(meta);
154 Py_XDECREF(mkw);
155 Py_DECREF(bases);
156 return NULL;
157 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
159 if (cell != NULL) {
160 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs);
165 }
166 if (cls != NULL && PyCell_Check(cell)) {
167 Py_INCREF(cls);
168 PyCell_SET(cell, cls);
169 }
170 Py_DECREF(cell);
171 }
172 Py_DECREF(ns);
173 Py_DECREF(meta);
174 Py_XDECREF(mkw);
175 Py_DECREF(bases);
176 return cls;
177 }
178
179 PyDoc_STRVAR(build_class_doc,
180 "__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
181 \n\
182 Internal helper function used by the class statement.");
183
184 static PyObject *
185 builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
186 {
187 static char *kwlist[] = {"name", "globals", "locals", "fromlist",
188 "level", 0};
189 PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;
190 int level = -1;
191
192 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|OOOi:__import__",
193 kwlist, &name, &globals, &locals, &fromlist, &level))
194 return NULL;
195 return PyImport_ImportModuleLevelObject(name, globals, locals,
196 fromlist, level);
197 }
198
199 PyDoc_STRVAR(import_doc,
200 "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
201 \n\
202 Import a module. Because this function is meant for use by the Python\n\
203 interpreter and not for general use it is better to use\n\
204 importlib.import_module() to programmatically import a module.\n\
205 \n\
206 The globals argument is only used to determine the context;\n\
207 they are not modified. The locals argument is unused. The fromlist\n\
208 should be a list of names to emulate ``from name import ...'', or an\n\
209 empty list to emulate ``import name''.\n\
210 When importing a module from a package, note that __import__('A.B', ...)\n\
211 returns package A when fromlist is empty, but its submodule B when\n\
212 fromlist is not empty. Level is used to determine whether to perform \n\
213 absolute or relative imports. -1 is the original strategy of attempting\n\
214 both absolute and relative imports, 0 is absolute, a positive number\n\
215 is the number of parent directories to search relative to the current module.");
216
217
218 static PyObject *
219 builtin_abs(PyObject *self, PyObject *v)
220 {
221 return PyNumber_Absolute(v);
222 }
223
224 PyDoc_STRVAR(abs_doc,
225 "abs(number) -> number\n\
226 \n\
227 Return the absolute value of the argument.");
228
229 static PyObject *
230 builtin_all(PyObject *self, PyObject *v)
231 {
232 PyObject *it, *item;
233 PyObject *(*iternext)(PyObject *);
234 int cmp;
235
236 it = PyObject_GetIter(v);
237 if (it == NULL)
238 return NULL;
239 iternext = *Py_TYPE(it)->tp_iternext;
240
241 for (;;) {
242 item = iternext(it);
243 if (item == NULL)
244 break;
245 cmp = PyObject_IsTrue(item);
246 Py_DECREF(item);
247 if (cmp < 0) {
248 Py_DECREF(it);
249 return NULL;
250 }
251 if (cmp == 0) {
252 Py_DECREF(it);
253 Py_RETURN_FALSE;
254 }
255 }
256 Py_DECREF(it);
257 if (PyErr_Occurred()) {
258 if (PyErr_ExceptionMatches(PyExc_StopIteration))
259 PyErr_Clear();
260 else
261 return NULL;
262 }
263 Py_RETURN_TRUE;
264 }
265
266 PyDoc_STRVAR(all_doc,
267 "all(iterable) -> bool\n\
268 \n\
269 Return True if bool(x) is True for all values x in the iterable.");
270
271 static PyObject *
272 builtin_any(PyObject *self, PyObject *v)
273 {
274 PyObject *it, *item;
275 PyObject *(*iternext)(PyObject *);
276 int cmp;
277
278 it = PyObject_GetIter(v);
279 if (it == NULL)
280 return NULL;
281 iternext = *Py_TYPE(it)->tp_iternext;
282
283 for (;;) {
284 item = iternext(it);
285 if (item == NULL)
286 break;
287 cmp = PyObject_IsTrue(item);
288 Py_DECREF(item);
289 if (cmp < 0) {
290 Py_DECREF(it);
291 return NULL;
292 }
293 if (cmp == 1) {
294 Py_DECREF(it);
295 Py_RETURN_TRUE;
296 }
297 }
298 Py_DECREF(it);
299 if (PyErr_Occurred()) {
300 if (PyErr_ExceptionMatches(PyExc_StopIteration))
301 PyErr_Clear();
302 else
303 return NULL;
304 }
305 Py_RETURN_FALSE;
306 }
307
308 PyDoc_STRVAR(any_doc,
309 "any(iterable) -> bool\n\
310 \n\
311 Return True if bool(x) is True for any x in the iterable.");
312
313 static PyObject *
314 builtin_ascii(PyObject *self, PyObject *v)
315 {
316 return PyObject_ASCII(v);
317 }
318
319 PyDoc_STRVAR(ascii_doc,
320 "ascii(object) -> string\n\
321 \n\
322 As repr(), return a string containing a printable representation of an\n\
323 object, but escape the non-ASCII characters in the string returned by\n\
324 repr() using \\x, \\u or \\U escapes. This generates a string similar\n\
325 to that returned by repr() in Python 2.");
326
327
328 static PyObject *
329 builtin_bin(PyObject *self, PyObject *v)
330 {
331 return PyNumber_ToBase(v, 2);
332 }
333
334 PyDoc_STRVAR(bin_doc,
335 "bin(number) -> string\n\
336 \n\
337 Return the binary representation of an integer.");
338
339
340 static PyObject *
341 builtin_callable(PyObject *self, PyObject *v)
342 {
343 return PyBool_FromLong((long)PyCallable_Check(v));
344 }
345
346 PyDoc_STRVAR(callable_doc,
347 "callable(object) -> bool\n\
348 \n\
349 Return whether the object is callable (i.e., some kind of function).\n\
350 Note that classes are callable, as are instances of classes with a\n\
351 __call__() method.");
352
353
354 typedef struct {
355 PyObject_HEAD
356 PyObject *func;
357 PyObject *it;
358 } filterobject;
359
360 static PyObject *
361 filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
362 {
363 PyObject *func, *seq;
364 PyObject *it;
365 filterobject *lz;
366
367 if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
368 return NULL;
369
370 if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
371 return NULL;
372
373 /* Get iterator. */
374 it = PyObject_GetIter(seq);
375 if (it == NULL)
376 return NULL;
377
378 /* create filterobject structure */
379 lz = (filterobject *)type->tp_alloc(type, 0);
380 if (lz == NULL) {
381 Py_DECREF(it);
382 return NULL;
383 }
384 Py_INCREF(func);
385 lz->func = func;
386 lz->it = it;
387
388 return (PyObject *)lz;
389 }
390
391 static void
392 filter_dealloc(filterobject *lz)
393 {
394 PyObject_GC_UnTrack(lz);
395 Py_XDECREF(lz->func);
396 Py_XDECREF(lz->it);
397 Py_TYPE(lz)->tp_free(lz);
398 }
399
400 static int
401 filter_traverse(filterobject *lz, visitproc visit, void *arg)
402 {
403 Py_VISIT(lz->it);
404 Py_VISIT(lz->func);
405 return 0;
406 }
407
408 static PyObject *
409 filter_next(filterobject *lz)
410 {
411 PyObject *item;
412 PyObject *it = lz->it;
413 long ok;
414 PyObject *(*iternext)(PyObject *);
415
416 iternext = *Py_TYPE(it)->tp_iternext;
417 for (;;) {
418 item = iternext(it);
419 if (item == NULL)
420 return NULL;
421
422 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
423 ok = PyObject_IsTrue(item);
424 } else {
425 PyObject *good;
426 good = PyObject_CallFunctionObjArgs(lz->func,
427 item, NULL);
428 if (good == NULL) {
429 Py_DECREF(item);
430 return NULL;
431 }
432 ok = PyObject_IsTrue(good);
433 Py_DECREF(good);
434 }
435 if (ok)
436 return item;
437 Py_DECREF(item);
438 }
439 }
440
441 PyDoc_STRVAR(filter_doc,
442 "filter(function or None, iterable) --> filter object\n\
443 \n\
444 Return an iterator yielding those items of iterable for which function(item)\n\
445 is true. If function is None, return the items that are true.");
446
447 PyTypeObject PyFilter_Type = {
448 PyVarObject_HEAD_INIT(&PyType_Type, 0)
449 "filter", /* tp_name */
450 sizeof(filterobject), /* tp_basicsize */
451 0, /* tp_itemsize */
452 /* methods */
453 (destructor)filter_dealloc, /* tp_dealloc */
454 0, /* tp_print */
455 0, /* tp_getattr */
456 0, /* tp_setattr */
457 0, /* tp_reserved */
458 0, /* tp_repr */
459 0, /* tp_as_number */
460 0, /* tp_as_sequence */
461 0, /* tp_as_mapping */
462 0, /* tp_hash */
463 0, /* tp_call */
464 0, /* tp_str */
465 PyObject_GenericGetAttr, /* tp_getattro */
466 0, /* tp_setattro */
467 0, /* tp_as_buffer */
468 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
469 Py_TPFLAGS_BASETYPE, /* tp_flags */
470 filter_doc, /* tp_doc */
471 (traverseproc)filter_traverse, /* tp_traverse */
472 0, /* tp_clear */
473 0, /* tp_richcompare */
474 0, /* tp_weaklistoffset */
475 PyObject_SelfIter, /* tp_iter */
476 (iternextfunc)filter_next, /* tp_iternext */
477 0, /* tp_methods */
478 0, /* tp_members */
479 0, /* tp_getset */
480 0, /* tp_base */
481 0, /* tp_dict */
482 0, /* tp_descr_get */
483 0, /* tp_descr_set */
484 0, /* tp_dictoffset */
485 0, /* tp_init */
486 PyType_GenericAlloc, /* tp_alloc */
487 filter_new, /* tp_new */
488 PyObject_GC_Del, /* tp_free */
489 };
490
491
492 static PyObject *
493 builtin_format(PyObject *self, PyObject *args)
494 {
495 PyObject *value;
496 PyObject *format_spec = NULL;
497
498 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
499 return NULL;
500
501 return PyObject_Format(value, format_spec);
502 }
503
504 PyDoc_STRVAR(format_doc,
505 "format(value[, format_spec]) -> string\n\
506 \n\
507 Returns value.__format__(format_spec)\n\
508 format_spec defaults to \"\"");
509
510 static PyObject *
511 builtin_chr(PyObject *self, PyObject *args)
512 {
513 int x;
514
515 if (!PyArg_ParseTuple(args, "i:chr", &x))
516 return NULL;
517
518 return PyUnicode_FromOrdinal(x);
519 }
520
521 PyDoc_STRVAR(chr_doc,
522 "chr(i) -> Unicode character\n\
523 \n\
524 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
525
526
527 static char *
528 source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
529 {
530 char *str;
531 Py_ssize_t size;
532
533 if (PyUnicode_Check(cmd)) {
534 cf->cf_flags |= PyCF_IGNORE_COOKIE;
535 str = PyUnicode_AsUTF8AndSize(cmd, &size);
536 if (str == NULL)
537 return NULL;
538 }
539 else if (!PyObject_CheckReadBuffer(cmd)) {
540 PyErr_Format(PyExc_TypeError,
541 "%s() arg 1 must be a %s object",
542 funcname, what);
543 return NULL;
544 }
545 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
546 return NULL;
547 }
548
549 if (strlen(str) != size) {
550 PyErr_SetString(PyExc_TypeError,
551 "source code string cannot contain null bytes");
552 return NULL;
553 }
554 return str;
555 }
556
557 static PyObject *
558 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
559 {
560 char *str;
561 PyObject *filename_obj;
562 char *filename;
563 char *startstr;
564 int mode = -1;
565 int dont_inherit = 0;
566 int supplied_flags = 0;
567 int optimize = -1;
568 int is_ast;
569 PyCompilerFlags cf;
570 PyObject *cmd;
571 static char *kwlist[] = {"source", "filename", "mode", "flags",
572 "dont_inherit", "optimize", NULL};
573 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
574 PyObject *result;
575
576 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist,
577 &cmd,
578 PyUnicode_FSConverter, &filename_obj,
579 &startstr, &supplied_flags,
580 &dont_inherit, &optimize))
581 return NULL;
582
583 filename = PyBytes_AS_STRING(filename_obj);
584 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
585
586 if (supplied_flags &
587 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
588 {
589 PyErr_SetString(PyExc_ValueError,
590 "compile(): unrecognised flags");
591 goto error;
592 }
593 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
594
595 if (optimize < -1 || optimize > 2) {
596 PyErr_SetString(PyExc_ValueError,
597 "compile(): invalid optimize value");
598 goto error;
599 }
600
601 if (!dont_inherit) {
602 PyEval_MergeCompilerFlags(&cf);
603 }
604
605 if (strcmp(startstr, "exec") == 0)
606 mode = 0;
607 else if (strcmp(startstr, "eval") == 0)
608 mode = 1;
609 else if (strcmp(startstr, "single") == 0)
610 mode = 2;
611 else {
612 PyErr_SetString(PyExc_ValueError,
613 "compile() arg 3 must be 'exec', 'eval' or 'single'");
614 goto error;
615 }
616
617 is_ast = PyAST_Check(cmd);
618 if (is_ast == -1)
619 goto error;
620 if (is_ast) {
621 if (supplied_flags & PyCF_ONLY_AST) {
622 Py_INCREF(cmd);
623 result = cmd;
624 }
625 else {
626 PyArena *arena;
627 mod_ty mod;
628
629 arena = PyArena_New();
630 mod = PyAST_obj2mod(cmd, arena, mode);
631 if (mod == NULL) {
632 PyArena_Free(arena);
633 goto error;
634 }
635 if (!PyAST_Validate(mod)) {
636 PyArena_Free(arena);
637 goto error;
638 }
639 result = (PyObject*)PyAST_CompileEx(mod, filename,
640 &cf, optimize, arena);
641 PyArena_Free(arena);
642 }
643 goto finally;
644 }
645
646 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
647 if (str == NULL)
648 goto error;
649
650 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
651 goto finally;
652
653 error:
654 result = NULL;
655 finally:
656 Py_DECREF(filename_obj);
657 return result;
658 }
659
660 PyDoc_STRVAR(compile_doc,
661 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
662 \n\
663 Compile the source string (a Python module, statement or expression)\n\
664 into a code object that can be executed by exec() or eval().\n\
665 The filename will be used for run-time error messages.\n\
666 The mode must be 'exec' to compile a module, 'single' to compile a\n\
667 single (interactive) statement, or 'eval' to compile an expression.\n\
668 The flags argument, if present, controls which future statements influence\n\
669 the compilation of the code.\n\
670 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
671 the effects of any future statements in effect in the code calling\n\
672 compile; if absent or zero these statements do influence the compilation,\n\
673 in addition to any features explicitly specified.");
674
675 static PyObject *
676 builtin_dir(PyObject *self, PyObject *args)
677 {
678 PyObject *arg = NULL;
679
680 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
681 return NULL;
682 return PyObject_Dir(arg);
683 }
684
685 PyDoc_STRVAR(dir_doc,
686 "dir([object]) -> list of strings\n"
687 "\n"
688 "If called without an argument, return the names in the current scope.\n"
689 "Else, return an alphabetized list of names comprising (some of) the attributes\n"
690 "of the given object, and of attributes reachable from it.\n"
691 "If the object supplies a method named __dir__, it will be used; otherwise\n"
692 "the default dir() logic is used and returns:\n"
693 " for a module object: the module's attributes.\n"
694 " for a class object: its attributes, and recursively the attributes\n"
695 " of its bases.\n"
696 " for any other object: its attributes, its class's attributes, and\n"
697 " recursively the attributes of its class's base classes.");
698
699 static PyObject *
700 builtin_divmod(PyObject *self, PyObject *args)
701 {
702 PyObject *v, *w;
703
704 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
705 return NULL;
706 return PyNumber_Divmod(v, w);
707 }
708
709 PyDoc_STRVAR(divmod_doc,
710 "divmod(x, y) -> (div, mod)\n\
711 \n\
712 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
713
714
715 static PyObject *
716 builtin_eval(PyObject *self, PyObject *args)
717 {
718 PyObject *cmd, *result, *tmp = NULL;
719 PyObject *globals = Py_None, *locals = Py_None;
720 char *str;
721 PyCompilerFlags cf;
722
723 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
724 return NULL;
725 if (locals != Py_None && !PyMapping_Check(locals)) {
726 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
727 return NULL;
728 }
729 if (globals != Py_None && !PyDict_Check(globals)) {
730 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
731 "globals must be a real dict; try eval(expr, {}, mapping)"
732 : "globals must be a dict");
733 return NULL;
734 }
735 if (globals == Py_None) {
736 globals = PyEval_GetGlobals();
737 if (locals == Py_None)
738 locals = PyEval_GetLocals();
739 }
740 else if (locals == Py_None)
741 locals = globals;
742
743 if (globals == NULL || locals == NULL) {
744 PyErr_SetString(PyExc_TypeError,
745 "eval must be given globals and locals "
746 "when called without a frame");
747 return NULL;
748 }
749
750 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
751 if (PyDict_SetItemString(globals, "__builtins__",
752 PyEval_GetBuiltins()) != 0)
753 return NULL;
754 }
755
756 if (PyCode_Check(cmd)) {
757 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
758 PyErr_SetString(PyExc_TypeError,
759 "code object passed to eval() may not contain free variables");
760 return NULL;
761 }
762 return PyEval_EvalCode(cmd, globals, locals);
763 }
764
765 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
766 str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
767 if (str == NULL)
768 return NULL;
769
770 while (*str == ' ' || *str == '\t')
771 str++;
772
773 (void)PyEval_MergeCompilerFlags(&cf);
774 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
775 Py_XDECREF(tmp);
776 return result;
777 }
778
779 PyDoc_STRVAR(eval_doc,
780 "eval(source[, globals[, locals]]) -> value\n\
781 \n\
782 Evaluate the source in the context of globals and locals.\n\
783 The source may be a string representing a Python expression\n\
784 or a code object as returned by compile().\n\
785 The globals must be a dictionary and locals can be any mapping,\n\
786 defaulting to the current globals and locals.\n\
787 If only globals is given, locals defaults to it.\n");
788
789 static PyObject *
790 builtin_exec(PyObject *self, PyObject *args)
791 {
792 PyObject *v;
793 PyObject *prog, *globals = Py_None, *locals = Py_None;
794
795 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
796 return NULL;
797
798 if (globals == Py_None) {
799 globals = PyEval_GetGlobals();
800 if (locals == Py_None) {
801 locals = PyEval_GetLocals();
802 }
803 if (!globals || !locals) {
804 PyErr_SetString(PyExc_SystemError,
805 "globals and locals cannot be NULL");
806 return NULL;
807 }
808 }
809 else if (locals == Py_None)
810 locals = globals;
811
812 if (!PyDict_Check(globals)) {
813 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
814 globals->ob_type->tp_name);
815 return NULL;
816 }
817 if (!PyMapping_Check(locals)) {
818 PyErr_Format(PyExc_TypeError,
819 "arg 3 must be a mapping or None, not %.100s",
820 locals->ob_type->tp_name);
821 return NULL;
822 }
823 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
824 if (PyDict_SetItemString(globals, "__builtins__",
825 PyEval_GetBuiltins()) != 0)
826 return NULL;
827 }
828
829 if (PyCode_Check(prog)) {
830 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
831 PyErr_SetString(PyExc_TypeError,
832 "code object passed to exec() may not "
833 "contain free variables");
834 return NULL;
835 }
836 v = PyEval_EvalCode(prog, globals, locals);
837 }
838 else {
839 char *str;
840 PyCompilerFlags cf;
841 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
842 str = source_as_string(prog, "exec",
843 "string, bytes or code", &cf);
844 if (str == NULL)
845 return NULL;
846 if (PyEval_MergeCompilerFlags(&cf))
847 v = PyRun_StringFlags(str, Py_file_input, globals,
848 locals, &cf);
849 else
850 v = PyRun_String(str, Py_file_input, globals, locals);
851 }
852 if (v == NULL)
853 return NULL;
854 Py_DECREF(v);
855 Py_RETURN_NONE;
856 }
857
858 PyDoc_STRVAR(exec_doc,
859 "exec(object[, globals[, locals]])\n\
860 \n\
861 Read and execute code from an object, which can be a string or a code\n\
862 object.\n\
863 The globals and locals are dictionaries, defaulting to the current\n\
864 globals and locals. If only globals is given, locals defaults to it.");
865
866
867 static PyObject *
868 builtin_getattr(PyObject *self, PyObject *args)
869 {
870 PyObject *v, *result, *dflt = NULL;
871 PyObject *name;
872
873 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
874 return NULL;
875
876 if (!PyUnicode_Check(name)) {
877 PyErr_SetString(PyExc_TypeError,
878 "getattr(): attribute name must be string");
879 return NULL;
880 }
881 result = PyObject_GetAttr(v, name);
882 if (result == NULL && dflt != NULL &&
883 PyErr_ExceptionMatches(PyExc_AttributeError))
884 {
885 PyErr_Clear();
886 Py_INCREF(dflt);
887 result = dflt;
888 }
889 return result;
890 }
891
892 PyDoc_STRVAR(getattr_doc,
893 "getattr(object, name[, default]) -> value\n\
894 \n\
895 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
896 When a default argument is given, it is returned when the attribute doesn't\n\
897 exist; without it, an exception is raised in that case.");
898
899
900 static PyObject *
901 builtin_globals(PyObject *self)
902 {
903 PyObject *d;
904
905 d = PyEval_GetGlobals();
906 Py_XINCREF(d);
907 return d;
908 }
909
910 PyDoc_STRVAR(globals_doc,
911 "globals() -> dictionary\n\
912 \n\
913 Return the dictionary containing the current scope's global variables.");
914
915
916 static PyObject *
917 builtin_hasattr(PyObject *self, PyObject *args)
918 {
919 PyObject *v;
920 PyObject *name;
921
922 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
923 return NULL;
924 if (!PyUnicode_Check(name)) {
925 PyErr_SetString(PyExc_TypeError,
926 "hasattr(): attribute name must be string");
927 return NULL;
928 }
929 v = PyObject_GetAttr(v, name);
930 if (v == NULL) {
931 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
932 PyErr_Clear();
933 Py_RETURN_FALSE;
934 }
935 return NULL;
936 }
937 Py_DECREF(v);
938 Py_RETURN_TRUE;
939 }
940
941 PyDoc_STRVAR(hasattr_doc,
942 "hasattr(object, name) -> bool\n\
943 \n\
944 Return whether the object has an attribute with the given name.\n\
945 (This is done by calling getattr(object, name) and catching AttributeError.)");
946
947
948 static PyObject *
949 builtin_id(PyObject *self, PyObject *v)
950 {
951 return PyLong_FromVoidPtr(v);
952 }
953
954 PyDoc_STRVAR(id_doc,
955 "id(object) -> integer\n\
956 \n\
957 Return the identity of an object. This is guaranteed to be unique among\n\
958 simultaneously existing objects. (Hint: it's the object's memory address.)");
959
960
961 /* map object ************************************************************/
962
963 typedef struct {
964 PyObject_HEAD
965 PyObject *iters;
966 PyObject *func;
967 } mapobject;
968
969 static PyObject *
970 map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
971 {
972 PyObject *it, *iters, *func;
973 mapobject *lz;
974 Py_ssize_t numargs, i;
975
976 if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
977 return NULL;
978
979 numargs = PyTuple_Size(args);
980 if (numargs < 2) {
981 PyErr_SetString(PyExc_TypeError,
982 "map() must have at least two arguments.");
983 return NULL;
984 }
985
986 iters = PyTuple_New(numargs-1);
987 if (iters == NULL)
988 return NULL;
989
990 for (i=1 ; i<numargs ; i++) {
991 /* Get iterator. */
992 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
993 if (it == NULL) {
994 Py_DECREF(iters);
995 return NULL;
996 }
997 PyTuple_SET_ITEM(iters, i-1, it);
998 }
999
1000 /* create mapobject structure */
1001 lz = (mapobject *)type->tp_alloc(type, 0);
1002 if (lz == NULL) {
1003 Py_DECREF(iters);
1004 return NULL;
1005 }
1006 lz->iters = iters;
1007 func = PyTuple_GET_ITEM(args, 0);
1008 Py_INCREF(func);
1009 lz->func = func;
1010
1011 return (PyObject *)lz;
1012 }
1013
1014 static void
1015 map_dealloc(mapobject *lz)
1016 {
1017 PyObject_GC_UnTrack(lz);
1018 Py_XDECREF(lz->iters);
1019 Py_XDECREF(lz->func);
1020 Py_TYPE(lz)->tp_free(lz);
1021 }
1022
1023 static int
1024 map_traverse(mapobject *lz, visitproc visit, void *arg)
1025 {
1026 Py_VISIT(lz->iters);
1027 Py_VISIT(lz->func);
1028 return 0;
1029 }
1030
1031 static PyObject *
1032 map_next(mapobject *lz)
1033 {
1034 PyObject *val;
1035 PyObject *argtuple;
1036 PyObject *result;
1037 Py_ssize_t numargs, i;
1038
1039 numargs = PyTuple_Size(lz->iters);
1040 argtuple = PyTuple_New(numargs);
1041 if (argtuple == NULL)
1042 return NULL;
1043
1044 for (i=0 ; i<numargs ; i++) {
1045 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1046 if (val == NULL) {
1047 Py_DECREF(argtuple);
1048 return NULL;
1049 }
1050 PyTuple_SET_ITEM(argtuple, i, val);
1051 }
1052 result = PyObject_Call(lz->func, argtuple, NULL);
1053 Py_DECREF(argtuple);
1054 return result;
1055 }
1056
1057 PyDoc_STRVAR(map_doc,
1058 "map(func, *iterables) --> map object\n\
1059 \n\
1060 Make an iterator that computes the function using arguments from\n\
1061 each of the iterables. Stops when the shortest iterable is exhausted.");
1062
1063 PyTypeObject PyMap_Type = {
1064 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1065 "map", /* tp_name */
1066 sizeof(mapobject), /* tp_basicsize */
1067 0, /* tp_itemsize */
1068 /* methods */
1069 (destructor)map_dealloc, /* tp_dealloc */
1070 0, /* tp_print */
1071 0, /* tp_getattr */
1072 0, /* tp_setattr */
1073 0, /* tp_reserved */
1074 0, /* tp_repr */
1075 0, /* tp_as_number */
1076 0, /* tp_as_sequence */
1077 0, /* tp_as_mapping */
1078 0, /* tp_hash */
1079 0, /* tp_call */
1080 0, /* tp_str */
1081 PyObject_GenericGetAttr, /* tp_getattro */
1082 0, /* tp_setattro */
1083 0, /* tp_as_buffer */
1084 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1085 Py_TPFLAGS_BASETYPE, /* tp_flags */
1086 map_doc, /* tp_doc */
1087 (traverseproc)map_traverse, /* tp_traverse */
1088 0, /* tp_clear */
1089 0, /* tp_richcompare */
1090 0, /* tp_weaklistoffset */
1091 PyObject_SelfIter, /* tp_iter */
1092 (iternextfunc)map_next, /* tp_iternext */
1093 0, /* tp_methods */
1094 0, /* tp_members */
1095 0, /* tp_getset */
1096 0, /* tp_base */
1097 0, /* tp_dict */
1098 0, /* tp_descr_get */
1099 0, /* tp_descr_set */
1100 0, /* tp_dictoffset */
1101 0, /* tp_init */
1102 PyType_GenericAlloc, /* tp_alloc */
1103 map_new, /* tp_new */
1104 PyObject_GC_Del, /* tp_free */
1105 };
1106
1107 static PyObject *
1108 builtin_next(PyObject *self, PyObject *args)
1109 {
1110 PyObject *it, *res;
1111 PyObject *def = NULL;
1112
1113 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1114 return NULL;
1115 if (!PyIter_Check(it)) {
1116 PyErr_Format(PyExc_TypeError,
1117 "'%.200s' object is not an iterator",
1118 it->ob_type->tp_name);
1119 return NULL;
1120 }
1121
1122 res = (*it->ob_type->tp_iternext)(it);
1123 if (res != NULL) {
1124 return res;
1125 } else if (def != NULL) {
1126 if (PyErr_Occurred()) {
1127 if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1128 return NULL;
1129 PyErr_Clear();
1130 }
1131 Py_INCREF(def);
1132 return def;
1133 } else if (PyErr_Occurred()) {
1134 return NULL;
1135 } else {
1136 PyErr_SetNone(PyExc_StopIteration);
1137 return NULL;
1138 }
1139 }
1140
1141 PyDoc_STRVAR(next_doc,
1142 "next(iterator[, default])\n\
1143 \n\
1144 Return the next item from the iterator. If default is given and the iterator\n\
1145 is exhausted, it is returned instead of raising StopIteration.");
1146
1147
1148 static PyObject *
1149 builtin_setattr(PyObject *self, PyObject *args)
1150 {
1151 PyObject *v;
1152 PyObject *name;
1153 PyObject *value;
1154
1155 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1156 return NULL;
1157 if (PyObject_SetAttr(v, name, value) != 0)
1158 return NULL;
1159 Py_INCREF(Py_None);
1160 return Py_None;
1161 }
1162
1163 PyDoc_STRVAR(setattr_doc,
1164 "setattr(object, name, value)\n\
1165 \n\
1166 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1167 ``x.y = v''.");
1168
1169
1170 static PyObject *
1171 builtin_delattr(PyObject *self, PyObject *args)
1172 {
1173 PyObject *v;
1174 PyObject *name;
1175
1176 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1177 return NULL;
1178 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1179 return NULL;
1180 Py_INCREF(Py_None);
1181 return Py_None;
1182 }
1183
1184 PyDoc_STRVAR(delattr_doc,
1185 "delattr(object, name)\n\
1186 \n\
1187 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1188 ``del x.y''.");
1189
1190
1191 static PyObject *
1192 builtin_hash(PyObject *self, PyObject *v)
1193 {
1194 Py_hash_t x;
1195
1196 x = PyObject_Hash(v);
1197 if (x == -1)
1198 return NULL;
1199 return PyLong_FromSsize_t(x);
1200 }
1201
1202 PyDoc_STRVAR(hash_doc,
1203 "hash(object) -> integer\n\
1204 \n\
1205 Return a hash value for the object. Two objects with the same value have\n\
1206 the same hash value. The reverse is not necessarily true, but likely.");
1207
1208
1209 static PyObject *
1210 builtin_hex(PyObject *self, PyObject *v)
1211 {
1212 return PyNumber_ToBase(v, 16);
1213 }
1214
1215 PyDoc_STRVAR(hex_doc,
1216 "hex(number) -> string\n\
1217 \n\
1218 Return the hexadecimal representation of an integer.");
1219
1220
1221 static PyObject *
1222 builtin_iter(PyObject *self, PyObject *args)
1223 {
1224 PyObject *v, *w = NULL;
1225
1226 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1227 return NULL;
1228 if (w == NULL)
1229 return PyObject_GetIter(v);
1230 if (!PyCallable_Check(v)) {
1231 PyErr_SetString(PyExc_TypeError,
1232 "iter(v, w): v must be callable");
1233 return NULL;
1234 }
1235 return PyCallIter_New(v, w);
1236 }
1237
1238 PyDoc_STRVAR(iter_doc,
1239 "iter(iterable) -> iterator\n\
1240 iter(callable, sentinel) -> iterator\n\
1241 \n\
1242 Get an iterator from an object. In the first form, the argument must\n\
1243 supply its own iterator, or be a sequence.\n\
1244 In the second form, the callable is called until it returns the sentinel.");
1245
1246
1247 static PyObject *
1248 builtin_len(PyObject *self, PyObject *v)
1249 {
1250 Py_ssize_t res;
1251
1252 res = PyObject_Size(v);
1253 if (res < 0 && PyErr_Occurred())
1254 return NULL;
1255 return PyLong_FromSsize_t(res);
1256 }
1257
1258 PyDoc_STRVAR(len_doc,
1259 "len(object) -> integer\n\
1260 \n\
1261 Return the number of items of a sequence or mapping.");
1262
1263
1264 static PyObject *
1265 builtin_locals(PyObject *self)
1266 {
1267 PyObject *d;
1268
1269 d = PyEval_GetLocals();
1270 Py_XINCREF(d);
1271 return d;
1272 }
1273
1274 PyDoc_STRVAR(locals_doc,
1275 "locals() -> dictionary\n\
1276 \n\
1277 Update and return a dictionary containing the current scope's local variables.");
1278
1279
1280 static PyObject *
1281 min_max(PyObject *args, PyObject *kwds, int op)
1282 {
1283 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1284 const char *name = op == Py_LT ? "min" : "max";
1285
1286 if (PyTuple_Size(args) > 1)
1287 v = args;
1288 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
1289 return NULL;
1290
1291 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
1292 keyfunc = PyDict_GetItemString(kwds, "key");
1293 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
1294 PyErr_Format(PyExc_TypeError,
1295 "%s() got an unexpected keyword argument", name);
1296 return NULL;
1297 }
1298 Py_INCREF(keyfunc);
1299 }
1300
1301 it = PyObject_GetIter(v);
1302 if (it == NULL) {
1303 Py_XDECREF(keyfunc);
1304 return NULL;
1305 }
1306
1307 maxitem = NULL; /* the result */
1308 maxval = NULL; /* the value associated with the result */
1309 while (( item = PyIter_Next(it) )) {
1310 /* get the value from the key function */
1311 if (keyfunc != NULL) {
1312 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1313 if (val == NULL)
1314 goto Fail_it_item;
1315 }
1316 /* no key function; the value is the item */
1317 else {
1318 val = item;
1319 Py_INCREF(val);
1320 }
1321
1322 /* maximum value and item are unset; set them */
1323 if (maxval == NULL) {
1324 maxitem = item;
1325 maxval = val;
1326 }
1327 /* maximum value and item are set; update them as necessary */
1328 else {
1329 int cmp = PyObject_RichCompareBool(val, maxval, op);
1330 if (cmp < 0)
1331 goto Fail_it_item_and_val;
1332 else if (cmp > 0) {
1333 Py_DECREF(maxval);
1334 Py_DECREF(maxitem);
1335 maxval = val;
1336 maxitem = item;
1337 }
1338 else {
1339 Py_DECREF(item);
1340 Py_DECREF(val);
1341 }
1342 }
1343 }
1344 if (PyErr_Occurred())
1345 goto Fail_it;
1346 if (maxval == NULL) {
1347 PyErr_Format(PyExc_ValueError,
1348 "%s() arg is an empty sequence", name);
1349 assert(maxitem == NULL);
1350 }
1351 else
1352 Py_DECREF(maxval);
1353 Py_DECREF(it);
1354 Py_XDECREF(keyfunc);
1355 return maxitem;
1356
1357 Fail_it_item_and_val:
1358 Py_DECREF(val);
1359 Fail_it_item:
1360 Py_DECREF(item);
1361 Fail_it:
1362 Py_XDECREF(maxval);
1363 Py_XDECREF(maxitem);
1364 Py_DECREF(it);
1365 Py_XDECREF(keyfunc);
1366 return NULL;
1367 }
1368
1369 static PyObject *
1370 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1371 {
1372 return min_max(args, kwds, Py_LT);
1373 }
1374
1375 PyDoc_STRVAR(min_doc,
1376 "min(iterable[, key=func]) -> value\n\
1377 min(a, b, c, ...[, key=func]) -> value\n\
1378 \n\
1379 With a single iterable argument, return its smallest item.\n\
1380 With two or more arguments, return the smallest argument.");
1381
1382
1383 static PyObject *
1384 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1385 {
1386 return min_max(args, kwds, Py_GT);
1387 }
1388
1389 PyDoc_STRVAR(max_doc,
1390 "max(iterable[, key=func]) -> value\n\
1391 max(a, b, c, ...[, key=func]) -> value\n\
1392 \n\
1393 With a single iterable argument, return its largest item.\n\
1394 With two or more arguments, return the largest argument.");
1395
1396
1397 static PyObject *
1398 builtin_oct(PyObject *self, PyObject *v)
1399 {
1400 return PyNumber_ToBase(v, 8);
1401 }
1402
1403 PyDoc_STRVAR(oct_doc,
1404 "oct(number) -> string\n\
1405 \n\
1406 Return the octal representation of an integer.");
1407
1408
1409 static PyObject *
1410 builtin_ord(PyObject *self, PyObject* obj)
1411 {
1412 long ord;
1413 Py_ssize_t size;
1414
1415 if (PyBytes_Check(obj)) {
1416 size = PyBytes_GET_SIZE(obj);
1417 if (size == 1) {
1418 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1419 return PyLong_FromLong(ord);
1420 }
1421 }
1422 else if (PyUnicode_Check(obj)) {
1423 if (PyUnicode_READY(obj) == -1)
1424 return NULL;
1425 size = PyUnicode_GET_LENGTH(obj);
1426 if (size == 1) {
1427 ord = (long)PyUnicode_READ_CHAR(obj, 0);
1428 return PyLong_FromLong(ord);
1429 }
1430 }
1431 else if (PyByteArray_Check(obj)) {
1432 /* XXX Hopefully this is temporary */
1433 size = PyByteArray_GET_SIZE(obj);
1434 if (size == 1) {
1435 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1436 return PyLong_FromLong(ord);
1437 }
1438 }
1439 else {
1440 PyErr_Format(PyExc_TypeError,
1441 "ord() expected string of length 1, but " \
1442 "%.200s found", obj->ob_type->tp_name);
1443 return NULL;
1444 }
1445
1446 PyErr_Format(PyExc_TypeError,
1447 "ord() expected a character, "
1448 "but string of length %zd found",
1449 size);
1450 return NULL;
1451 }
1452
1453 PyDoc_VAR(ord_doc) = PyDoc_STR(
1454 "ord(c) -> integer\n\
1455 \n\
1456 Return the integer ordinal of a one-character string."
1457 )
1458 #ifndef Py_UNICODE_WIDE
1459 PyDoc_STR(
1460 "\nA valid surrogate pair is also accepted."
1461 )
1462 #endif
1463 ;
1464
1465
1466 static PyObject *
1467 builtin_pow(PyObject *self, PyObject *args)
1468 {
1469 PyObject *v, *w, *z = Py_None;
1470
1471 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1472 return NULL;
1473 return PyNumber_Power(v, w, z);
1474 }
1475
1476 PyDoc_STRVAR(pow_doc,
1477 "pow(x, y[, z]) -> number\n\
1478 \n\
1479 With two arguments, equivalent to x**y. With three arguments,\n\
1480 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
1481
1482
1483
1484 static PyObject *
1485 builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1486 {
1487 static char *kwlist[] = {"sep", "end", "file", 0};
1488 static PyObject *dummy_args;
1489 PyObject *sep = NULL, *end = NULL, *file = NULL;
1490 int i, err;
1491
1492 if (dummy_args == NULL) {
1493 if (!(dummy_args = PyTuple_New(0)))
1494 return NULL;
1495 }
1496 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1497 kwlist, &sep, &end, &file))
1498 return NULL;
1499 if (file == NULL || file == Py_None) {
1500 file = PySys_GetObject("stdout");
1501 /* sys.stdout may be None when FILE* stdout isn't connected */
1502 if (file == Py_None)
1503 Py_RETURN_NONE;
1504 }
1505
1506 if (sep == Py_None) {
1507 sep = NULL;
1508 }
1509 else if (sep && !PyUnicode_Check(sep)) {
1510 PyErr_Format(PyExc_TypeError,
1511 "sep must be None or a string, not %.200s",
1512 sep->ob_type->tp_name);
1513 return NULL;
1514 }
1515 if (end == Py_None) {
1516 end = NULL;
1517 }
1518 else if (end && !PyUnicode_Check(end)) {
1519 PyErr_Format(PyExc_TypeError,
1520 "end must be None or a string, not %.200s",
1521 end->ob_type->tp_name);
1522 return NULL;
1523 }
1524
1525 for (i = 0; i < PyTuple_Size(args); i++) {
1526 if (i > 0) {
1527 if (sep == NULL)
1528 err = PyFile_WriteString(" ", file);
1529 else
1530 err = PyFile_WriteObject(sep, file,
1531 Py_PRINT_RAW);
1532 if (err)
1533 return NULL;
1534 }
1535 err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1536 Py_PRINT_RAW);
1537 if (err)
1538 return NULL;
1539 }
1540
1541 if (end == NULL)
1542 err = PyFile_WriteString("\n", file);
1543 else
1544 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1545 if (err)
1546 return NULL;
1547
1548 Py_RETURN_NONE;
1549 }
1550
1551 PyDoc_STRVAR(print_doc,
1552 "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
1553 \n\
1554 Prints the values to a stream, or to sys.stdout by default.\n\
1555 Optional keyword arguments:\n\
1556 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1557 sep: string inserted between values, default a space.\n\
1558 end: string appended after the last value, default a newline.");
1559
1560
1561 static PyObject *
1562 builtin_input(PyObject *self, PyObject *args)
1563 {
1564 PyObject *promptarg = NULL;
1565 PyObject *fin = PySys_GetObject("stdin");
1566 PyObject *fout = PySys_GetObject("stdout");
1567 PyObject *ferr = PySys_GetObject("stderr");
1568 PyObject *tmp;
1569 long fd;
1570 int tty;
1571
1572 /* Parse arguments */
1573 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1574 return NULL;
1575
1576 /* Check that stdin/out/err are intact */
1577 if (fin == NULL || fin == Py_None) {
1578 PyErr_SetString(PyExc_RuntimeError,
1579 "input(): lost sys.stdin");
1580 return NULL;
1581 }
1582 if (fout == NULL || fout == Py_None) {
1583 PyErr_SetString(PyExc_RuntimeError,
1584 "input(): lost sys.stdout");
1585 return NULL;
1586 }
1587 if (ferr == NULL || ferr == Py_None) {
1588 PyErr_SetString(PyExc_RuntimeError,
1589 "input(): lost sys.stderr");
1590 return NULL;
1591 }
1592
1593 /* First of all, flush stderr */
1594 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1595 if (tmp == NULL)
1596 PyErr_Clear();
1597 else
1598 Py_DECREF(tmp);
1599
1600 /* We should only use (GNU) readline if Python's sys.stdin and
1601 sys.stdout are the same as C's stdin and stdout, because we
1602 need to pass it those. */
1603 tmp = _PyObject_CallMethodId(fin, &PyId_fileno, "");
1604 if (tmp == NULL) {
1605 PyErr_Clear();
1606 tty = 0;
1607 }
1608 else {
1609 fd = PyLong_AsLong(tmp);
1610 Py_DECREF(tmp);
1611 if (fd < 0 && PyErr_Occurred())
1612 return NULL;
1613 tty = fd == fileno(stdin) && isatty(fd);
1614 }
1615 if (tty) {
1616 tmp = _PyObject_CallMethodId(fout, &PyId_fileno, "");
1617 if (tmp == NULL)
1618 PyErr_Clear();
1619 else {
1620 fd = PyLong_AsLong(tmp);
1621 Py_DECREF(tmp);
1622 if (fd < 0 && PyErr_Occurred())
1623 return NULL;
1624 tty = fd == fileno(stdout) && isatty(fd);
1625 }
1626 }
1627
1628 /* If we're interactive, use (GNU) readline */
1629 if (tty) {
1630 PyObject *po = NULL;
1631 char *prompt;
1632 char *s = NULL;
1633 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1634 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1635 char *stdin_encoding_str, *stdin_errors_str;
1636 PyObject *result;
1637 size_t len;
1638 _Py_IDENTIFIER(encoding);
1639 _Py_IDENTIFIER(errors);
1640
1641 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
1642 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
1643 if (!stdin_encoding || !stdin_errors)
1644 /* stdin is a text stream, so it must have an
1645 encoding. */
1646 goto _readline_errors;
1647 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1648 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1649 if (!stdin_encoding_str || !stdin_errors_str)
1650 goto _readline_errors;
1651 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
1652 if (tmp == NULL)
1653 PyErr_Clear();
1654 else
1655 Py_DECREF(tmp);
1656 if (promptarg != NULL) {
1657 /* We have a prompt, encode it as stdout would */
1658 char *stdout_encoding_str, *stdout_errors_str;
1659 PyObject *stringpo;
1660 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
1661 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
1662 if (!stdout_encoding || !stdout_errors)
1663 goto _readline_errors;
1664 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1665 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1666 if (!stdout_encoding_str || !stdout_errors_str)
1667 goto _readline_errors;
1668 stringpo = PyObject_Str(promptarg);
1669 if (stringpo == NULL)
1670 goto _readline_errors;
1671 po = PyUnicode_AsEncodedString(stringpo,
1672 stdout_encoding_str, stdout_errors_str);
1673 Py_CLEAR(stdout_encoding);
1674 Py_CLEAR(stdout_errors);
1675 Py_CLEAR(stringpo);
1676 if (po == NULL)
1677 goto _readline_errors;
1678 prompt = PyBytes_AsString(po);
1679 if (prompt == NULL)
1680 goto _readline_errors;
1681 }
1682 else {
1683 po = NULL;
1684 prompt = "";
1685 }
1686 s = PyOS_Readline(stdin, stdout, prompt);
1687 if (s == NULL) {
1688 if (!PyErr_Occurred())
1689 PyErr_SetNone(PyExc_KeyboardInterrupt);
1690 goto _readline_errors;
1691 }
1692
1693 len = strlen(s);
1694 if (len == 0) {
1695 PyErr_SetNone(PyExc_EOFError);
1696 result = NULL;
1697 }
1698 else {
1699 if (len > PY_SSIZE_T_MAX) {
1700 PyErr_SetString(PyExc_OverflowError,
1701 "input: input too long");
1702 result = NULL;
1703 }
1704 else {
1705 len--; /* strip trailing '\n' */
1706 if (len != 0 && s[len-1] == '\r')
1707 len--; /* strip trailing '\r' */
1708 result = PyUnicode_Decode(s, len, stdin_encoding_str,
1709 stdin_errors_str);
1710 }
1711 }
1712 Py_DECREF(stdin_encoding);
1713 Py_DECREF(stdin_errors);
1714 Py_XDECREF(po);
1715 PyMem_FREE(s);
1716 return result;
1717 _readline_errors:
1718 Py_XDECREF(stdin_encoding);
1719 Py_XDECREF(stdout_encoding);
1720 Py_XDECREF(stdin_errors);
1721 Py_XDECREF(stdout_errors);
1722 Py_XDECREF(po);
1723 return NULL;
1724 }
1725
1726 /* Fallback if we're not interactive */
1727 if (promptarg != NULL) {
1728 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1729 return NULL;
1730 }
1731 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
1732 if (tmp == NULL)
1733 PyErr_Clear();
1734 else
1735 Py_DECREF(tmp);
1736 return PyFile_GetLine(fin, -1);
1737 }
1738
1739 PyDoc_STRVAR(input_doc,
1740 "input([prompt]) -> string\n\
1741 \n\
1742 Read a string from standard input. The trailing newline is stripped.\n\
1743 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1744 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1745 is printed without a trailing newline before reading.");
1746
1747
1748 static PyObject *
1749 builtin_repr(PyObject *self, PyObject *v)
1750 {
1751 return PyObject_Repr(v);
1752 }
1753
1754 PyDoc_STRVAR(repr_doc,
1755 "repr(object) -> string\n\
1756 \n\
1757 Return the canonical string representation of the object.\n\
1758 For most object types, eval(repr(object)) == object.");
1759
1760
1761 static PyObject *
1762 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
1763 {
1764 static PyObject *round_str = NULL;
1765 PyObject *ndigits = NULL;
1766 static char *kwlist[] = {"number", "ndigits", 0};
1767 PyObject *number, *round;
1768
1769 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1770 kwlist, &number, &ndigits))
1771 return NULL;
1772
1773 if (Py_TYPE(number)->tp_dict == NULL) {
1774 if (PyType_Ready(Py_TYPE(number)) < 0)
1775 return NULL;
1776 }
1777
1778 if (round_str == NULL) {
1779 round_str = PyUnicode_InternFromString("__round__");
1780 if (round_str == NULL)
1781 return NULL;
1782 }
1783
1784 round = _PyType_Lookup(Py_TYPE(number), round_str);
1785 if (round == NULL) {
1786 PyErr_Format(PyExc_TypeError,
1787 "type %.100s doesn't define __round__ method",
1788 Py_TYPE(number)->tp_name);
1789 return NULL;
1790 }
1791
1792 if (ndigits == NULL)
1793 return PyObject_CallFunction(round, "O", number);
1794 else
1795 return PyObject_CallFunction(round, "OO", number, ndigits);
1796 }
1797
1798 PyDoc_STRVAR(round_doc,
1799 "round(number[, ndigits]) -> number\n\
1800 \n\
1801 Round a number to a given precision in decimal digits (default 0 digits).\n\
1802 This returns an int when called with one argument, otherwise the\n\
1803 same type as the number. ndigits may be negative.");
1804
1805
1806 static PyObject *
1807 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1808 {
1809 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1810 PyObject *callable;
1811 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1812 int reverse;
1813 _Py_IDENTIFIER(sort);
1814
1815 /* args 1-3 should match listsort in Objects/listobject.c */
1816 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1817 kwlist, &seq, &keyfunc, &reverse))
1818 return NULL;
1819
1820 newlist = PySequence_List(seq);
1821 if (newlist == NULL)
1822 return NULL;
1823
1824 callable = _PyObject_GetAttrId(newlist, &PyId_sort);
1825 if (callable == NULL) {
1826 Py_DECREF(newlist);
1827 return NULL;
1828 }
1829
1830 newargs = PyTuple_GetSlice(args, 1, 4);
1831 if (newargs == NULL) {
1832 Py_DECREF(newlist);
1833 Py_DECREF(callable);
1834 return NULL;
1835 }
1836
1837 v = PyObject_Call(callable, newargs, kwds);
1838 Py_DECREF(newargs);
1839 Py_DECREF(callable);
1840 if (v == NULL) {
1841 Py_DECREF(newlist);
1842 return NULL;
1843 }
1844 Py_DECREF(v);
1845 return newlist;
1846 }
1847
1848 PyDoc_STRVAR(sorted_doc,
1849 "sorted(iterable, key=None, reverse=False) --> new sorted list");
1850
1851 static PyObject *
1852 builtin_vars(PyObject *self, PyObject *args)
1853 {
1854 PyObject *v = NULL;
1855 PyObject *d;
1856
1857 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1858 return NULL;
1859 if (v == NULL) {
1860 d = PyEval_GetLocals();
1861 if (d == NULL) {
1862 if (!PyErr_Occurred())
1863 PyErr_SetString(PyExc_SystemError,
1864 "vars(): no locals!?");
1865 }
1866 else
1867 Py_INCREF(d);
1868 }
1869 else {
1870 _Py_IDENTIFIER(__dict__);
1871 d = _PyObject_GetAttrId(v, &PyId___dict__);
1872 if (d == NULL) {
1873 PyErr_SetString(PyExc_TypeError,
1874 "vars() argument must have __dict__ attribute");
1875 return NULL;
1876 }
1877 }
1878 return d;
1879 }
1880
1881 PyDoc_STRVAR(vars_doc,
1882 "vars([object]) -> dictionary\n\
1883 \n\
1884 Without arguments, equivalent to locals().\n\
1885 With an argument, equivalent to object.__dict__.");
1886
1887 static PyObject*
1888 builtin_sum(PyObject *self, PyObject *args)
1889 {
1890 PyObject *seq;
1891 PyObject *result = NULL;
1892 PyObject *temp, *item, *iter;
1893
1894 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1895 return NULL;
1896
1897 iter = PyObject_GetIter(seq);
1898 if (iter == NULL)
1899 return NULL;
1900
1901 if (result == NULL) {
1902 result = PyLong_FromLong(0);
1903 if (result == NULL) {
1904 Py_DECREF(iter);
1905 return NULL;
1906 }
1907 } else {
1908 /* reject string values for 'start' parameter */
1909 if (PyUnicode_Check(result)) {
1910 PyErr_SetString(PyExc_TypeError,
1911 "sum() can't sum strings [use ''.join(seq) instead]");
1912 Py_DECREF(iter);
1913 return NULL;
1914 }
1915 if (PyBytes_Check(result)) {
1916 PyErr_SetString(PyExc_TypeError,
1917 "sum() can't sum bytes [use b''.join(seq) instead]");
1918 Py_DECREF(iter);
1919 return NULL;
1920 }
1921 if (PyByteArray_Check(result)) {
1922 PyErr_SetString(PyExc_TypeError,
1923 "sum() can't sum bytearray [use b''.join(seq) instead]");
1924 Py_DECREF(iter);
1925 return NULL;
1926 }
1927
1928 Py_INCREF(result);
1929 }
1930
1931 #ifndef SLOW_SUM
1932 /* Fast addition by keeping temporary sums in C instead of new Python objects.
1933 Assumes all inputs are the same type. If the assumption fails, default
1934 to the more general routine.
1935 */
1936 if (PyLong_CheckExact(result)) {
1937 int overflow;
1938 long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1939 /* If this already overflowed, don't even enter the loop. */
1940 if (overflow == 0) {
1941 Py_DECREF(result);
1942 result = NULL;
1943 }
1944 while(result == NULL) {
1945 item = PyIter_Next(iter);
1946 if (item == NULL) {
1947 Py_DECREF(iter);
1948 if (PyErr_Occurred())
1949 return NULL;
1950 return PyLong_FromLong(i_result);
1951 }
1952 if (PyLong_CheckExact(item)) {
1953 long b = PyLong_AsLongAndOverflow(item, &overflow);
1954 long x = i_result + b;
1955 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
1956 i_result = x;
1957 Py_DECREF(item);
1958 continue;
1959 }
1960 }
1961 /* Either overflowed or is not an int. Restore real objects and process normally */
1962 result = PyLong_FromLong(i_result);
1963 temp = PyNumber_Add(result, item);
1964 Py_DECREF(result);
1965 Py_DECREF(item);
1966 result = temp;
1967 if (result == NULL) {
1968 Py_DECREF(iter);
1969 return NULL;
1970 }
1971 }
1972 }
1973
1974 if (PyFloat_CheckExact(result)) {
1975 double f_result = PyFloat_AS_DOUBLE(result);
1976 Py_DECREF(result);
1977 result = NULL;
1978 while(result == NULL) {
1979 item = PyIter_Next(iter);
1980 if (item == NULL) {
1981 Py_DECREF(iter);
1982 if (PyErr_Occurred())
1983 return NULL;
1984 return PyFloat_FromDouble(f_result);
1985 }
1986 if (PyFloat_CheckExact(item)) {
1987 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1988 f_result += PyFloat_AS_DOUBLE(item);
1989 PyFPE_END_PROTECT(f_result)
1990 Py_DECREF(item);
1991 continue;
1992 }
1993 if (PyLong_CheckExact(item)) {
1994 long value;
1995 int overflow;
1996 value = PyLong_AsLongAndOverflow(item, &overflow);
1997 if (!overflow) {
1998 PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
1999 f_result += (double)value;
2000 PyFPE_END_PROTECT(f_result)
2001 Py_DECREF(item);
2002 continue;
2003 }
2004 }
2005 result = PyFloat_FromDouble(f_result);
2006 temp = PyNumber_Add(result, item);
2007 Py_DECREF(result);
2008 Py_DECREF(item);
2009 result = temp;
2010 if (result == NULL) {
2011 Py_DECREF(iter);
2012 return NULL;
2013 }
2014 }
2015 }
2016 #endif
2017
2018 for(;;) {
2019 item = PyIter_Next(iter);
2020 if (item == NULL) {
2021 /* error, or end-of-sequence */
2022 if (PyErr_Occurred()) {
2023 Py_DECREF(result);
2024 result = NULL;
2025 }
2026 break;
2027 }
2028 /* It's tempting to use PyNumber_InPlaceAdd instead of
2029 PyNumber_Add here, to avoid quadratic running time
2030 when doing 'sum(list_of_lists, [])'. However, this
2031 would produce a change in behaviour: a snippet like
2032
2033 empty = []
2034 sum([[x] for x in range(10)], empty)
2035
2036 would change the value of empty. */
2037 temp = PyNumber_Add(result, item);
2038 Py_DECREF(result);
2039 Py_DECREF(item);
2040 result = temp;
2041 if (result == NULL)
2042 break;
2043 }
2044 Py_DECREF(iter);
2045 return result;
2046 }
2047
2048 PyDoc_STRVAR(sum_doc,
2049 "sum(iterable[, start]) -> value\n\
2050 \n\
2051 Returns the sum of an iterable of numbers (NOT strings) plus the value\n\
2052 of parameter 'start' (which defaults to 0). When the iterable is\n\
2053 empty, returns start.");
2054
2055
2056 static PyObject *
2057 builtin_isinstance(PyObject *self, PyObject *args)
2058 {
2059 PyObject *inst;
2060 PyObject *cls;
2061 int retval;
2062
2063 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
2064 return NULL;
2065
2066 retval = PyObject_IsInstance(inst, cls);
2067 if (retval < 0)
2068 return NULL;
2069 return PyBool_FromLong(retval);
2070 }
2071
2072 PyDoc_STRVAR(isinstance_doc,
2073 "isinstance(object, class-or-type-or-tuple) -> bool\n\
2074 \n\
2075 Return whether an object is an instance of a class or of a subclass thereof.\n\
2076 With a type as second argument, return whether that is the object's type.\n\
2077 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
2078 isinstance(x, A) or isinstance(x, B) or ... (etc.).");
2079
2080
2081 static PyObject *
2082 builtin_issubclass(PyObject *self, PyObject *args)
2083 {
2084 PyObject *derived;
2085 PyObject *cls;
2086 int retval;
2087
2088 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2089 return NULL;
2090
2091 retval = PyObject_IsSubclass(derived, cls);
2092 if (retval < 0)
2093 return NULL;
2094 return PyBool_FromLong(retval);
2095 }
2096
2097 PyDoc_STRVAR(issubclass_doc,
2098 "issubclass(C, B) -> bool\n\
2099 \n\
2100 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2101 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2102 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2103
2104
2105 typedef struct {
2106 PyObject_HEAD
2107 Py_ssize_t tuplesize;
2108 PyObject *ittuple; /* tuple of iterators */
2109 PyObject *result;
2110 } zipobject;
2111
2112 static PyObject *
2113 zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2114 {
2115 zipobject *lz;
2116 Py_ssize_t i;
2117 PyObject *ittuple; /* tuple of iterators */
2118 PyObject *result;
2119 Py_ssize_t tuplesize = PySequence_Length(args);
2120
2121 if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2122 return NULL;
2123
2124 /* args must be a tuple */
2125 assert(PyTuple_Check(args));
2126
2127 /* obtain iterators */
2128 ittuple = PyTuple_New(tuplesize);
2129 if (ittuple == NULL)
2130 return NULL;
2131 for (i=0; i < tuplesize; ++i) {
2132 PyObject *item = PyTuple_GET_ITEM(args, i);
2133 PyObject *it = PyObject_GetIter(item);
2134 if (it == NULL) {
2135 if (PyErr_ExceptionMatches(PyExc_TypeError))
2136 PyErr_Format(PyExc_TypeError,
2137 "zip argument #%zd must support iteration",
2138 i+1);
2139 Py_DECREF(ittuple);
2140 return NULL;
2141 }
2142 PyTuple_SET_ITEM(ittuple, i, it);
2143 }
2144
2145 /* create a result holder */
2146 result = PyTuple_New(tuplesize);
2147 if (result == NULL) {
2148 Py_DECREF(ittuple);
2149 return NULL;
2150 }
2151 for (i=0 ; i < tuplesize ; i++) {
2152 Py_INCREF(Py_None);
2153 PyTuple_SET_ITEM(result, i, Py_None);
2154 }
2155
2156 /* create zipobject structure */
2157 lz = (zipobject *)type->tp_alloc(type, 0);
2158 if (lz == NULL) {
2159 Py_DECREF(ittuple);
2160 Py_DECREF(result);
2161 return NULL;
2162 }
2163 lz->ittuple = ittuple;
2164 lz->tuplesize = tuplesize;
2165 lz->result = result;
2166
2167 return (PyObject *)lz;
2168 }
2169
2170 static void
2171 zip_dealloc(zipobject *lz)
2172 {
2173 PyObject_GC_UnTrack(lz);
2174 Py_XDECREF(lz->ittuple);
2175 Py_XDECREF(lz->result);
2176 Py_TYPE(lz)->tp_free(lz);
2177 }
2178
2179 static int
2180 zip_traverse(zipobject *lz, visitproc visit, void *arg)
2181 {
2182 Py_VISIT(lz->ittuple);
2183 Py_VISIT(lz->result);
2184 return 0;
2185 }
2186
2187 static PyObject *
2188 zip_next(zipobject *lz)
2189 {
2190 Py_ssize_t i;
2191 Py_ssize_t tuplesize = lz->tuplesize;
2192 PyObject *result = lz->result;
2193 PyObject *it;
2194 PyObject *item;
2195 PyObject *olditem;
2196
2197 if (tuplesize == 0)
2198 return NULL;
2199 if (Py_REFCNT(result) == 1) {
2200 Py_INCREF(result);
2201 for (i=0 ; i < tuplesize ; i++) {
2202 it = PyTuple_GET_ITEM(lz->ittuple, i);
2203 item = (*Py_TYPE(it)->tp_iternext)(it);
2204 if (item == NULL) {
2205 Py_DECREF(result);
2206 return NULL;
2207 }
2208 olditem = PyTuple_GET_ITEM(result, i);
2209 PyTuple_SET_ITEM(result, i, item);
2210 Py_DECREF(olditem);
2211 }
2212 } else {
2213 result = PyTuple_New(tuplesize);
2214 if (result == NULL)
2215 return NULL;
2216 for (i=0 ; i < tuplesize ; i++) {
2217 it = PyTuple_GET_ITEM(lz->ittuple, i);
2218 item = (*Py_TYPE(it)->tp_iternext)(it);
2219 if (item == NULL) {
2220 Py_DECREF(result);
2221 return NULL;
2222 }
2223 PyTuple_SET_ITEM(result, i, item);
2224 }
2225 }
2226 return result;
2227 }
2228
2229 PyDoc_STRVAR(zip_doc,
2230 "zip(iter1 [,iter2 [...]]) --> zip object\n\
2231 \n\
2232 Return a zip object whose .__next__() method returns a tuple where\n\
2233 the i-th element comes from the i-th iterable argument. The .__next__()\n\
2234 method continues until the shortest iterable in the argument sequence\n\
2235 is exhausted and then it raises StopIteration.");
2236
2237 PyTypeObject PyZip_Type = {
2238 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2239 "zip", /* tp_name */
2240 sizeof(zipobject), /* tp_basicsize */
2241 0, /* tp_itemsize */
2242 /* methods */
2243 (destructor)zip_dealloc, /* tp_dealloc */
2244 0, /* tp_print */
2245 0, /* tp_getattr */
2246 0, /* tp_setattr */
2247 0, /* tp_reserved */
2248 0, /* tp_repr */
2249 0, /* tp_as_number */
2250 0, /* tp_as_sequence */
2251 0, /* tp_as_mapping */
2252 0, /* tp_hash */
2253 0, /* tp_call */
2254 0, /* tp_str */
2255 PyObject_GenericGetAttr, /* tp_getattro */
2256 0, /* tp_setattro */
2257 0, /* tp_as_buffer */
2258 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2259 Py_TPFLAGS_BASETYPE, /* tp_flags */
2260 zip_doc, /* tp_doc */
2261 (traverseproc)zip_traverse, /* tp_traverse */
2262 0, /* tp_clear */
2263 0, /* tp_richcompare */
2264 0, /* tp_weaklistoffset */
2265 PyObject_SelfIter, /* tp_iter */
2266 (iternextfunc)zip_next, /* tp_iternext */
2267 0, /* tp_methods */
2268 0, /* tp_members */
2269 0, /* tp_getset */
2270 0, /* tp_base */
2271 0, /* tp_dict */
2272 0, /* tp_descr_get */
2273 0, /* tp_descr_set */
2274 0, /* tp_dictoffset */
2275 0, /* tp_init */
2276 PyType_GenericAlloc, /* tp_alloc */
2277 zip_new, /* tp_new */
2278 PyObject_GC_Del, /* tp_free */
2279 };
2280
2281
2282 static PyMethodDef builtin_methods[] = {
2283 {"__build_class__", (PyCFunction)builtin___build_class__,
2284 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2285 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
2286 {"abs", builtin_abs, METH_O, abs_doc},
2287 {"all", builtin_all, METH_O, all_doc},
2288 {"any", builtin_any, METH_O, any_doc},
2289 {"ascii", builtin_ascii, METH_O, ascii_doc},
2290 {"bin", builtin_bin, METH_O, bin_doc},
2291 {"callable", builtin_callable, METH_O, callable_doc},
2292 {"chr", builtin_chr, METH_VARARGS, chr_doc},
2293 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
2294 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
2295 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2296 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
2297 {"eval", builtin_eval, METH_VARARGS, eval_doc},
2298 {"exec", builtin_exec, METH_VARARGS, exec_doc},
2299 {"format", builtin_format, METH_VARARGS, format_doc},
2300 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2301 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
2302 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
2303 {"hash", builtin_hash, METH_O, hash_doc},
2304 {"hex", builtin_hex, METH_O, hex_doc},
2305 {"id", builtin_id, METH_O, id_doc},
2306 {"input", builtin_input, METH_VARARGS, input_doc},
2307 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
2308 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
2309 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2310 {"len", builtin_len, METH_O, len_doc},
2311 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
2312 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
2313 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
2314 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc},
2315 {"oct", builtin_oct, METH_O, oct_doc},
2316 {"ord", builtin_ord, METH_O, ord_doc},
2317 {"pow", builtin_pow, METH_VARARGS, pow_doc},
2318 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
2319 {"repr", builtin_repr, METH_O, repr_doc},
2320 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
2321 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
2322 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
2323 {"sum", builtin_sum, METH_VARARGS, sum_doc},
2324 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2325 {NULL, NULL},
2326 };
2327
2328 PyDoc_STRVAR(builtin_doc,
2329 "Built-in functions, exceptions, and other objects.\n\
2330 \n\
2331 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2332
2333 static struct PyModuleDef builtinsmodule = {
2334 PyModuleDef_HEAD_INIT,
2335 "builtins",
2336 builtin_doc,
2337 -1, /* multiple "initialization" just copies the module dict. */
2338 builtin_methods,
2339 NULL,
2340 NULL,
2341 NULL,
2342 NULL
2343 };
2344
2345
2346 PyObject *
2347 _PyBuiltin_Init(void)
2348 {
2349 PyObject *mod, *dict, *debug;
2350 mod = PyModule_Create(&builtinsmodule);
2351 if (mod == NULL)
2352 return NULL;
2353 dict = PyModule_GetDict(mod);
2354
2355 #ifdef Py_TRACE_REFS
2356 /* "builtins" exposes a number of statically allocated objects
2357 * that, before this code was added in 2.3, never showed up in
2358 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2359 * result, programs leaking references to None and False (etc)
2360 * couldn't be diagnosed by examining sys.getobjects(0).
2361 */
2362 #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2363 #else
2364 #define ADD_TO_ALL(OBJECT) (void)0
2365 #endif
2366
2367 #define SETBUILTIN(NAME, OBJECT) \
2368 if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
2369 return NULL; \
2370 ADD_TO_ALL(OBJECT)
2371
2372 SETBUILTIN("None", Py_None);
2373 SETBUILTIN("Ellipsis", Py_Ellipsis);
2374 SETBUILTIN("NotImplemented", Py_NotImplemented);
2375 SETBUILTIN("False", Py_False);
2376 SETBUILTIN("True", Py_True);
2377 SETBUILTIN("bool", &PyBool_Type);
2378 SETBUILTIN("memoryview", &PyMemoryView_Type);
2379 SETBUILTIN("bytearray", &PyByteArray_Type);
2380 SETBUILTIN("bytes", &PyBytes_Type);
2381 SETBUILTIN("classmethod", &PyClassMethod_Type);
2382 SETBUILTIN("complex", &PyComplex_Type);
2383 SETBUILTIN("dict", &PyDict_Type);
2384 SETBUILTIN("enumerate", &PyEnum_Type);
2385 SETBUILTIN("filter", &PyFilter_Type);
2386 SETBUILTIN("float", &PyFloat_Type);
2387 SETBUILTIN("frozenset", &PyFrozenSet_Type);
2388 SETBUILTIN("property", &PyProperty_Type);
2389 SETBUILTIN("int", &PyLong_Type);
2390 SETBUILTIN("list", &PyList_Type);
2391 SETBUILTIN("map", &PyMap_Type);
2392 SETBUILTIN("object", &PyBaseObject_Type);
2393 SETBUILTIN("range", &PyRange_Type);
2394 SETBUILTIN("reversed", &PyReversed_Type);
2395 SETBUILTIN("set", &PySet_Type);
2396 SETBUILTIN("slice", &PySlice_Type);
2397 SETBUILTIN("staticmethod", &PyStaticMethod_Type);
2398 SETBUILTIN("str", &PyUnicode_Type);
2399 SETBUILTIN("super", &PySuper_Type);
2400 SETBUILTIN("tuple", &PyTuple_Type);
2401 SETBUILTIN("type", &PyType_Type);
2402 SETBUILTIN("zip", &PyZip_Type);
2403 debug = PyBool_FromLong(Py_OptimizeFlag == 0);
2404 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2405 Py_XDECREF(debug);
2406 return NULL;
2407 }
2408 Py_XDECREF(debug);
2409
2410 return mod;
2411 #undef ADD_TO_ALL
2412 #undef SETBUILTIN
2413 }