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