~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Python/bltinmodule.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

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