1
/* Built-in functions */
4
#include "Python-ast.h"
12
/* The default encoding used by the platform file system APIs
13
Can remain NULL for all platforms that don't have such a concept
15
Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the
16
values for Py_FileSystemDefaultEncoding!
18
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
19
const char *Py_FileSystemDefaultEncoding = "mbcs";
20
int Py_HasFileSystemDefaultEncoding = 1;
21
#elif defined(__APPLE__)
22
const char *Py_FileSystemDefaultEncoding = "utf-8";
23
int Py_HasFileSystemDefaultEncoding = 1;
25
const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
26
int Py_HasFileSystemDefaultEncoding = 0;
30
_Py_SetFileSystemEncoding(PyObject *s)
33
if (!PyUnicode_Check(s)) {
34
PyErr_BadInternalCall();
37
defenc = _PyUnicode_AsDefaultEncodedString(s, NULL);
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;
49
builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
51
PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
53
Py_ssize_t nargs, nbases;
56
if (!PyTuple_Check(args)) {
57
PyErr_SetString(PyExc_TypeError,
58
"__build_class__: args is not a tuple");
61
nargs = PyTuple_GET_SIZE(args);
63
PyErr_SetString(PyExc_TypeError,
64
"__build_class__: not enough arguments");
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");
74
bases = PyTuple_GetSlice(args, 2, nargs);
84
mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
89
meta = PyDict_GetItemString(mkw, "metaclass");
92
if (PyDict_DelItemString(mkw, "metaclass") < 0) {
101
if (PyTuple_GET_SIZE(bases) == 0)
102
meta = (PyObject *) (&PyType_Type);
104
PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
105
meta = (PyObject *) (base0->ob_type);
109
prep = PyObject_GetAttrString(meta, "__prepare__");
115
PyObject *pargs = PyTuple_Pack(2, name, bases);
123
ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
133
cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
136
margs = PyTuple_Pack(3, name, bases, ns);
138
cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
141
if (cls != NULL && PyCell_Check(cell)) {
143
PyCell_SET(cell, cls);
154
PyDoc_STRVAR(build_class_doc,
155
"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
157
Internal helper function used by the class statement.");
160
builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
162
static char *kwlist[] = {"name", "globals", "locals", "fromlist",
165
PyObject *globals = NULL;
166
PyObject *locals = NULL;
167
PyObject *fromlist = NULL;
170
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
171
kwlist, &name, &globals, &locals, &fromlist, &level))
173
return PyImport_ImportModuleLevel(name, globals, locals,
177
PyDoc_STRVAR(import_doc,
178
"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\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.");
193
builtin_abs(PyObject *self, PyObject *v)
195
return PyNumber_Absolute(v);
198
PyDoc_STRVAR(abs_doc,
199
"abs(number) -> number\n\
201
Return the absolute value of the argument.");
204
builtin_all(PyObject *self, PyObject *v)
207
PyObject *(*iternext)(PyObject *);
210
it = PyObject_GetIter(v);
213
iternext = *Py_TYPE(it)->tp_iternext;
219
cmp = PyObject_IsTrue(item);
231
if (PyErr_Occurred()) {
232
if (PyErr_ExceptionMatches(PyExc_StopIteration))
240
PyDoc_STRVAR(all_doc,
241
"all(iterable) -> bool\n\
243
Return True if bool(x) is True for all values x in the iterable.");
246
builtin_any(PyObject *self, PyObject *v)
249
PyObject *(*iternext)(PyObject *);
252
it = PyObject_GetIter(v);
255
iternext = *Py_TYPE(it)->tp_iternext;
261
cmp = PyObject_IsTrue(item);
273
if (PyErr_Occurred()) {
274
if (PyErr_ExceptionMatches(PyExc_StopIteration))
282
PyDoc_STRVAR(any_doc,
283
"any(iterable) -> bool\n\
285
Return True if bool(x) is True for any x in the iterable.");
288
builtin_ascii(PyObject *self, PyObject *v)
290
return PyObject_ASCII(v);
293
PyDoc_STRVAR(ascii_doc,
294
"ascii(object) -> string\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.");
303
builtin_bin(PyObject *self, PyObject *v)
305
return PyNumber_ToBase(v, 2);
308
PyDoc_STRVAR(bin_doc,
309
"bin(number) -> string\n\
311
Return the binary representation of an integer or long integer.");
320
PyTypeObject PyFilter_Type;
323
filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
325
PyObject *func, *seq;
329
if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds))
332
if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
336
it = PyObject_GetIter(seq);
340
/* create filterobject structure */
341
lz = (filterobject *)type->tp_alloc(type, 0);
350
return (PyObject *)lz;
354
filter_dealloc(filterobject *lz)
356
PyObject_GC_UnTrack(lz);
357
Py_XDECREF(lz->func);
359
Py_TYPE(lz)->tp_free(lz);
363
filter_traverse(filterobject *lz, visitproc visit, void *arg)
371
filter_next(filterobject *lz)
374
PyObject *it = lz->it;
376
PyObject *(*iternext)(PyObject *);
378
iternext = *Py_TYPE(it)->tp_iternext;
384
if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
385
ok = PyObject_IsTrue(item);
388
good = PyObject_CallFunctionObjArgs(lz->func,
394
ok = PyObject_IsTrue(good);
403
PyDoc_STRVAR(filter_doc,
404
"filter(function or None, iterable) --> filter object\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.");
409
PyTypeObject PyFilter_Type = {
410
PyVarObject_HEAD_INIT(&PyType_Type, 0)
411
"filter", /* tp_name */
412
sizeof(filterobject), /* tp_basicsize */
415
(destructor)filter_dealloc, /* tp_dealloc */
421
0, /* tp_as_number */
422
0, /* tp_as_sequence */
423
0, /* tp_as_mapping */
427
PyObject_GenericGetAttr, /* tp_getattro */
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 */
435
0, /* tp_richcompare */
436
0, /* tp_weaklistoffset */
437
PyObject_SelfIter, /* tp_iter */
438
(iternextfunc)filter_next, /* tp_iternext */
444
0, /* tp_descr_get */
445
0, /* tp_descr_set */
446
0, /* tp_dictoffset */
448
PyType_GenericAlloc, /* tp_alloc */
449
filter_new, /* tp_new */
450
PyObject_GC_Del, /* tp_free */
455
builtin_format(PyObject *self, PyObject *args)
458
PyObject *format_spec = NULL;
460
if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec))
463
return PyObject_Format(value, format_spec);
466
PyDoc_STRVAR(format_doc,
467
"format(value[, format_spec]) -> string\n\
469
Returns value.__format__(format_spec)\n\
470
format_spec defaults to \"\"");
473
builtin_chr(PyObject *self, PyObject *args)
477
if (!PyArg_ParseTuple(args, "i:chr", &x))
480
return PyUnicode_FromOrdinal(x);
483
PyDoc_VAR(chr_doc) = PyDoc_STR(
484
"chr(i) -> Unicode character\n\
486
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."
488
#ifndef Py_UNICODE_WIDE
490
"\nIf 0x10000 <= i, a surrogate pair is returned."
497
source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
502
if (PyUnicode_Check(cmd)) {
503
cf->cf_flags |= PyCF_IGNORE_COOKIE;
504
cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL);
508
else if (!PyObject_CheckReadBuffer(cmd)) {
509
PyErr_Format(PyExc_TypeError,
510
"%s() arg 1 must be a %s object",
514
if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) {
517
if (strlen(str) != size) {
518
PyErr_SetString(PyExc_TypeError,
519
"source code string cannot contain null bytes");
526
builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
532
int dont_inherit = 0;
533
int supplied_flags = 0;
536
static char *kwlist[] = {"source", "filename", "mode", "flags",
537
"dont_inherit", NULL};
538
int start[] = {Py_file_input, Py_eval_input, Py_single_input};
540
if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
541
kwlist, &cmd, &filename, &startstr,
542
&supplied_flags, &dont_inherit))
545
cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
548
~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
550
PyErr_SetString(PyExc_ValueError,
551
"compile(): unrecognised flags");
554
/* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
557
PyEval_MergeCompilerFlags(&cf);
560
if (strcmp(startstr, "exec") == 0)
562
else if (strcmp(startstr, "eval") == 0)
564
else if (strcmp(startstr, "single") == 0)
567
PyErr_SetString(PyExc_ValueError,
568
"compile() arg 3 must be 'exec', 'eval' or 'single'");
572
if (PyAST_Check(cmd)) {
574
if (supplied_flags & PyCF_ONLY_AST) {
582
arena = PyArena_New();
583
mod = PyAST_obj2mod(cmd, arena, mode);
588
result = (PyObject*)PyAST_Compile(mod, filename,
595
str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf);
599
return Py_CompileStringFlags(str, filename, start[mode], &cf);
602
PyDoc_STRVAR(compile_doc,
603
"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\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.");
618
builtin_dir(PyObject *self, PyObject *args)
620
PyObject *arg = NULL;
622
if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
624
return PyObject_Dir(arg);
627
PyDoc_STRVAR(dir_doc,
628
"dir([object]) -> list of strings\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"
638
" for any other object: its attributes, its class's attributes, and\n"
639
" recursively the attributes of its class's base classes.");
642
builtin_divmod(PyObject *self, PyObject *args)
646
if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
648
return PyNumber_Divmod(v, w);
651
PyDoc_STRVAR(divmod_doc,
652
"divmod(x, y) -> (div, mod)\n\
654
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
658
builtin_eval(PyObject *self, PyObject *args)
660
PyObject *cmd, *result, *tmp = NULL;
661
PyObject *globals = Py_None, *locals = Py_None;
665
if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
667
if (locals != Py_None && !PyMapping_Check(locals)) {
668
PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
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");
677
if (globals == Py_None) {
678
globals = PyEval_GetGlobals();
679
if (locals == Py_None)
680
locals = PyEval_GetLocals();
682
else if (locals == Py_None)
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");
692
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
693
if (PyDict_SetItemString(globals, "__builtins__",
694
PyEval_GetBuiltins()) != 0)
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");
704
return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
707
cf.cf_flags = PyCF_SOURCE_IS_UTF8;
708
str = source_as_string(cmd, "eval", "string, bytes or code", &cf);
712
while (*str == ' ' || *str == '\t')
715
(void)PyEval_MergeCompilerFlags(&cf);
716
result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
721
PyDoc_STRVAR(eval_doc,
722
"eval(source[, globals[, locals]]) -> value\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");
732
builtin_exec(PyObject *self, PyObject *args)
735
PyObject *prog, *globals = Py_None, *locals = Py_None;
738
if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
741
if (globals == Py_None) {
742
globals = PyEval_GetGlobals();
743
if (locals == Py_None) {
744
locals = PyEval_GetLocals();
747
if (!globals || !locals) {
748
PyErr_SetString(PyExc_SystemError,
749
"globals and locals cannot be NULL");
753
else if (locals == Py_None)
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);
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);
767
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
768
if (PyDict_SetItemString(globals, "__builtins__",
769
PyEval_GetBuiltins()) != 0)
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");
780
v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
785
cf.cf_flags = PyCF_SOURCE_IS_UTF8;
786
str = source_as_string(prog, "exec",
787
"string, bytes or code", &cf);
790
if (PyEval_MergeCompilerFlags(&cf))
791
v = PyRun_StringFlags(str, Py_file_input, globals,
794
v = PyRun_String(str, Py_file_input, globals, locals);
802
PyDoc_STRVAR(exec_doc,
803
"exec(object[, globals[, locals]])\n\
805
Read and execute code from a object, which can be a string or a code\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.");
812
builtin_getattr(PyObject *self, PyObject *args)
814
PyObject *v, *result, *dflt = NULL;
817
if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
820
if (!PyUnicode_Check(name)) {
821
PyErr_SetString(PyExc_TypeError,
822
"getattr(): attribute name must be string");
825
result = PyObject_GetAttr(v, name);
826
if (result == NULL && dflt != NULL &&
827
PyErr_ExceptionMatches(PyExc_AttributeError))
836
PyDoc_STRVAR(getattr_doc,
837
"getattr(object, name[, default]) -> value\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.");
845
builtin_globals(PyObject *self)
849
d = PyEval_GetGlobals();
854
PyDoc_STRVAR(globals_doc,
855
"globals() -> dictionary\n\
857
Return the dictionary containing the current scope's global variables.");
861
builtin_hasattr(PyObject *self, PyObject *args)
866
if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
868
if (!PyUnicode_Check(name)) {
869
PyErr_SetString(PyExc_TypeError,
870
"hasattr(): attribute name must be string");
873
v = PyObject_GetAttr(v, name);
875
if (!PyErr_ExceptionMatches(PyExc_Exception))
888
PyDoc_STRVAR(hasattr_doc,
889
"hasattr(object, name) -> bool\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.)");
896
builtin_id(PyObject *self, PyObject *v)
898
return PyLong_FromVoidPtr(v);
902
"id(object) -> integer\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.)");
908
/* map object ************************************************************/
916
PyTypeObject PyMap_Type;
919
map_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
921
PyObject *it, *iters, *func;
923
Py_ssize_t numargs, i;
925
if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds))
928
numargs = PyTuple_Size(args);
930
PyErr_SetString(PyExc_TypeError,
931
"map() must have at least two arguments.");
935
iters = PyTuple_New(numargs-1);
939
for (i=1 ; i<numargs ; i++) {
941
it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
946
PyTuple_SET_ITEM(iters, i-1, it);
949
/* create mapobject structure */
950
lz = (mapobject *)type->tp_alloc(type, 0);
956
func = PyTuple_GET_ITEM(args, 0);
960
return (PyObject *)lz;
964
map_dealloc(mapobject *lz)
966
PyObject_GC_UnTrack(lz);
967
Py_XDECREF(lz->iters);
968
Py_XDECREF(lz->func);
969
Py_TYPE(lz)->tp_free(lz);
973
map_traverse(mapobject *lz, visitproc visit, void *arg)
981
map_next(mapobject *lz)
986
Py_ssize_t numargs, i;
988
numargs = PyTuple_Size(lz->iters);
989
argtuple = PyTuple_New(numargs);
990
if (argtuple == NULL)
993
for (i=0 ; i<numargs ; i++) {
994
val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
999
PyTuple_SET_ITEM(argtuple, i, val);
1001
result = PyObject_Call(lz->func, argtuple, NULL);
1002
Py_DECREF(argtuple);
1006
PyDoc_STRVAR(map_doc,
1007
"map(func, *iterables) --> map object\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.");
1012
PyTypeObject PyMap_Type = {
1013
PyVarObject_HEAD_INIT(&PyType_Type, 0)
1014
"map", /* tp_name */
1015
sizeof(mapobject), /* tp_basicsize */
1016
0, /* tp_itemsize */
1018
(destructor)map_dealloc, /* tp_dealloc */
1022
0, /* tp_reserved */
1024
0, /* tp_as_number */
1025
0, /* tp_as_sequence */
1026
0, /* tp_as_mapping */
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 */
1038
0, /* tp_richcompare */
1039
0, /* tp_weaklistoffset */
1040
PyObject_SelfIter, /* tp_iter */
1041
(iternextfunc)map_next, /* tp_iternext */
1047
0, /* tp_descr_get */
1048
0, /* tp_descr_set */
1049
0, /* tp_dictoffset */
1051
PyType_GenericAlloc, /* tp_alloc */
1052
map_new, /* tp_new */
1053
PyObject_GC_Del, /* tp_free */
1057
builtin_next(PyObject *self, PyObject *args)
1060
PyObject *def = NULL;
1062
if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1064
if (!PyIter_Check(it)) {
1065
PyErr_Format(PyExc_TypeError,
1066
"%.200s object is not an iterator",
1067
it->ob_type->tp_name);
1071
res = (*it->ob_type->tp_iternext)(it);
1074
} else if (def != NULL) {
1075
if (PyErr_Occurred()) {
1076
if(!PyErr_ExceptionMatches(PyExc_StopIteration))
1082
} else if (PyErr_Occurred()) {
1085
PyErr_SetNone(PyExc_StopIteration);
1090
PyDoc_STRVAR(next_doc,
1091
"next(iterator[, default])\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.");
1098
builtin_setattr(PyObject *self, PyObject *args)
1104
if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
1106
if (PyObject_SetAttr(v, name, value) != 0)
1112
PyDoc_STRVAR(setattr_doc,
1113
"setattr(object, name, value)\n\
1115
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1120
builtin_delattr(PyObject *self, PyObject *args)
1125
if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
1127
if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1133
PyDoc_STRVAR(delattr_doc,
1134
"delattr(object, name)\n\
1136
Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1141
builtin_hash(PyObject *self, PyObject *v)
1145
x = PyObject_Hash(v);
1148
return PyLong_FromLong(x);
1151
PyDoc_STRVAR(hash_doc,
1152
"hash(object) -> integer\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.");
1159
builtin_hex(PyObject *self, PyObject *v)
1161
return PyNumber_ToBase(v, 16);
1164
PyDoc_STRVAR(hex_doc,
1165
"hex(number) -> string\n\
1167
Return the hexadecimal representation of an integer or long integer.");
1171
builtin_iter(PyObject *self, PyObject *args)
1173
PyObject *v, *w = NULL;
1175
if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1178
return PyObject_GetIter(v);
1179
if (!PyCallable_Check(v)) {
1180
PyErr_SetString(PyExc_TypeError,
1181
"iter(v, w): v must be callable");
1184
return PyCallIter_New(v, w);
1187
PyDoc_STRVAR(iter_doc,
1188
"iter(iterable) -> iterator\n\
1189
iter(callable, sentinel) -> iterator\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.");
1197
builtin_len(PyObject *self, PyObject *v)
1201
res = PyObject_Size(v);
1202
if (res < 0 && PyErr_Occurred())
1204
return PyLong_FromSsize_t(res);
1207
PyDoc_STRVAR(len_doc,
1208
"len(object) -> integer\n\
1210
Return the number of items of a sequence or mapping.");
1214
builtin_locals(PyObject *self)
1218
d = PyEval_GetLocals();
1223
PyDoc_STRVAR(locals_doc,
1224
"locals() -> dictionary\n\
1226
Update and return a dictionary containing the current scope's local variables.");
1230
min_max(PyObject *args, PyObject *kwds, int op)
1232
PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1233
const char *name = op == Py_LT ? "min" : "max";
1235
if (PyTuple_Size(args) > 1)
1237
else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
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);
1250
it = PyObject_GetIter(v);
1252
Py_XDECREF(keyfunc);
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);
1265
/* no key function; the value is the item */
1271
/* maximum value and item are unset; set them */
1272
if (maxval == NULL) {
1276
/* maximum value and item are set; update them as necessary */
1278
int cmp = PyObject_RichCompareBool(val, maxval, op);
1280
goto Fail_it_item_and_val;
1293
if (PyErr_Occurred())
1295
if (maxval == NULL) {
1296
PyErr_Format(PyExc_ValueError,
1297
"%s() arg is an empty sequence", name);
1298
assert(maxitem == NULL);
1303
Py_XDECREF(keyfunc);
1306
Fail_it_item_and_val:
1312
Py_XDECREF(maxitem);
1314
Py_XDECREF(keyfunc);
1319
builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1321
return min_max(args, kwds, Py_LT);
1324
PyDoc_STRVAR(min_doc,
1325
"min(iterable[, key=func]) -> value\n\
1326
min(a, b, c, ...[, key=func]) -> value\n\
1328
With a single iterable argument, return its smallest item.\n\
1329
With two or more arguments, return the smallest argument.");
1333
builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1335
return min_max(args, kwds, Py_GT);
1338
PyDoc_STRVAR(max_doc,
1339
"max(iterable[, key=func]) -> value\n\
1340
max(a, b, c, ...[, key=func]) -> value\n\
1342
With a single iterable argument, return its largest item.\n\
1343
With two or more arguments, return the largest argument.");
1347
builtin_oct(PyObject *self, PyObject *v)
1349
return PyNumber_ToBase(v, 8);
1352
PyDoc_STRVAR(oct_doc,
1353
"oct(number) -> string\n\
1355
Return the octal representation of an integer or long integer.");
1359
builtin_ord(PyObject *self, PyObject* obj)
1364
if (PyBytes_Check(obj)) {
1365
size = PyBytes_GET_SIZE(obj);
1367
ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
1368
return PyLong_FromLong(ord);
1371
else if (PyUnicode_Check(obj)) {
1372
size = PyUnicode_GET_SIZE(obj);
1374
ord = (long)*PyUnicode_AS_UNICODE(obj);
1375
return PyLong_FromLong(ord);
1377
#ifndef Py_UNICODE_WIDE
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)) +
1386
return PyLong_FromLong(ord);
1391
else if (PyByteArray_Check(obj)) {
1392
/* XXX Hopefully this is temporary */
1393
size = PyByteArray_GET_SIZE(obj);
1395
ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
1396
return PyLong_FromLong(ord);
1400
PyErr_Format(PyExc_TypeError,
1401
"ord() expected string of length 1, but " \
1402
"%.200s found", obj->ob_type->tp_name);
1406
PyErr_Format(PyExc_TypeError,
1407
"ord() expected a character, "
1408
"but string of length %zd found",
1413
PyDoc_VAR(ord_doc) = PyDoc_STR(
1414
"ord(c) -> integer\n\
1416
Return the integer ordinal of a one-character string."
1418
#ifndef Py_UNICODE_WIDE
1420
"\nA valid surrogate pair is also accepted."
1427
builtin_pow(PyObject *self, PyObject *args)
1429
PyObject *v, *w, *z = Py_None;
1431
if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
1433
return PyNumber_Power(v, w, z);
1436
PyDoc_STRVAR(pow_doc,
1437
"pow(x, y[, z]) -> number\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).");
1445
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1447
static char *kwlist[] = {"sep", "end", "file", 0};
1448
static PyObject *dummy_args;
1449
PyObject *sep = NULL, *end = NULL, *file = NULL;
1452
if (dummy_args == NULL) {
1453
if (!(dummy_args = PyTuple_New(0)))
1456
if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
1457
kwlist, &sep, &end, &file))
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)
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);
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);
1479
for (i = 0; i < PyTuple_Size(args); i++) {
1481
if (sep == NULL || sep == Py_None)
1482
err = PyFile_WriteString(" ", file);
1484
err = PyFile_WriteObject(sep, file,
1489
err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
1495
if (end == NULL || end == Py_None)
1496
err = PyFile_WriteString("\n", file);
1498
err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1505
PyDoc_STRVAR(print_doc,
1506
"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\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.");
1516
builtin_input(PyObject *self, PyObject *args)
1518
PyObject *promptarg = NULL;
1519
PyObject *fin = PySys_GetObject("stdin");
1520
PyObject *fout = PySys_GetObject("stdout");
1521
PyObject *ferr = PySys_GetObject("stderr");
1526
/* Parse arguments */
1527
if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
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");
1536
if (fout == NULL || fout == Py_None) {
1537
PyErr_SetString(PyExc_RuntimeError,
1538
"input(): lost sys.stdout");
1541
if (ferr == NULL || ferr == Py_None) {
1542
PyErr_SetString(PyExc_RuntimeError,
1543
"input(): lost sys.stderr");
1547
/* First of all, flush stderr */
1548
tmp = PyObject_CallMethod(ferr, "flush", "");
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", "");
1563
fd = PyLong_AsLong(tmp);
1565
if (fd < 0 && PyErr_Occurred())
1567
tty = fd == fileno(stdin) && isatty(fd);
1570
tmp = PyObject_CallMethod(fout, "fileno", "");
1574
fd = PyLong_AsLong(tmp);
1576
if (fd < 0 && PyErr_Occurred())
1578
tty = fd == fileno(stdout) && isatty(fd);
1582
/* If we're interactive, use (GNU) readline */
1587
PyObject *stdin_encoding;
1590
stdin_encoding = PyObject_GetAttrString(fin, "encoding");
1591
if (!stdin_encoding)
1592
/* stdin is a text stream, so it must have an
1595
tmp = PyObject_CallMethod(fout, "flush", "");
1600
if (promptarg != NULL) {
1602
PyObject *stdout_encoding;
1603
stdout_encoding = PyObject_GetAttrString(fout,
1605
if (stdout_encoding == NULL) {
1606
Py_DECREF(stdin_encoding);
1609
stringpo = PyObject_Str(promptarg);
1610
if (stringpo == NULL) {
1611
Py_DECREF(stdin_encoding);
1612
Py_DECREF(stdout_encoding);
1615
po = PyUnicode_AsEncodedString(stringpo,
1616
_PyUnicode_AsString(stdout_encoding), NULL);
1617
Py_DECREF(stdout_encoding);
1618
Py_DECREF(stringpo);
1620
Py_DECREF(stdin_encoding);
1623
prompt = PyBytes_AsString(po);
1624
if (prompt == NULL) {
1625
Py_DECREF(stdin_encoding);
1634
s = PyOS_Readline(stdin, stdout, prompt);
1637
if (!PyErr_Occurred())
1638
PyErr_SetNone(PyExc_KeyboardInterrupt);
1639
Py_DECREF(stdin_encoding);
1643
PyErr_SetNone(PyExc_EOFError);
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");
1654
result = PyUnicode_Decode
1656
_PyUnicode_AsString(stdin_encoding),
1660
Py_DECREF(stdin_encoding);
1665
/* Fallback if we're not interactive */
1666
if (promptarg != NULL) {
1667
if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0)
1670
tmp = PyObject_CallMethod(fout, "flush", "");
1675
return PyFile_GetLine(fin, -1);
1678
PyDoc_STRVAR(input_doc,
1679
"input([prompt]) -> string\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.");
1688
builtin_repr(PyObject *self, PyObject *v)
1690
return PyObject_Repr(v);
1693
PyDoc_STRVAR(repr_doc,
1694
"repr(object) -> string\n\
1696
Return the canonical string representation of the object.\n\
1697
For most object types, eval(repr(object)) == object.");
1701
builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
1703
static PyObject *round_str = NULL;
1704
PyObject *ndigits = NULL;
1705
static char *kwlist[] = {"number", "ndigits", 0};
1706
PyObject *number, *round;
1708
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1709
kwlist, &number, &ndigits))
1712
if (Py_TYPE(number)->tp_dict == NULL) {
1713
if (PyType_Ready(Py_TYPE(number)) < 0)
1717
if (round_str == NULL) {
1718
round_str = PyUnicode_InternFromString("__round__");
1719
if (round_str == NULL)
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);
1731
if (ndigits == NULL)
1732
return PyObject_CallFunction(round, "O", number);
1734
return PyObject_CallFunction(round, "OO", number, ndigits);
1737
PyDoc_STRVAR(round_doc,
1738
"round(number[, ndigits]) -> number\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.");
1746
builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1748
PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1750
static char *kwlist[] = {"iterable", "key", "reverse", 0};
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))
1758
newlist = PySequence_List(seq);
1759
if (newlist == NULL)
1762
callable = PyObject_GetAttrString(newlist, "sort");
1763
if (callable == NULL) {
1768
newargs = PyTuple_GetSlice(args, 1, 4);
1769
if (newargs == NULL) {
1771
Py_DECREF(callable);
1775
v = PyObject_Call(callable, newargs, kwds);
1777
Py_DECREF(callable);
1786
PyDoc_STRVAR(sorted_doc,
1787
"sorted(iterable, key=None, reverse=False) --> new sorted list");
1790
builtin_vars(PyObject *self, PyObject *args)
1795
if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1798
d = PyEval_GetLocals();
1800
if (!PyErr_Occurred())
1801
PyErr_SetString(PyExc_SystemError,
1802
"vars(): no locals!?");
1808
d = PyObject_GetAttrString(v, "__dict__");
1810
PyErr_SetString(PyExc_TypeError,
1811
"vars() argument must have __dict__ attribute");
1818
PyDoc_STRVAR(vars_doc,
1819
"vars([object]) -> dictionary\n\
1821
Without arguments, equivalent to locals().\n\
1822
With an argument, equivalent to object.__dict__.");
1825
builtin_sum(PyObject *self, PyObject *args)
1828
PyObject *result = NULL;
1829
PyObject *temp, *item, *iter;
1831
if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
1834
iter = PyObject_GetIter(seq);
1838
if (result == NULL) {
1839
result = PyLong_FromLong(0);
1840
if (result == NULL) {
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]");
1852
if (PyByteArray_Check(result)) {
1853
PyErr_SetString(PyExc_TypeError,
1854
"sum() can't sum bytes [use b''.join(seq) instead]");
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.
1867
if (PyLong_CheckExact(result)) {
1869
long i_result = PyLong_AsLongAndOverflow(result, &overflow);
1870
/* If this already overflowed, don't even enter the loop. */
1871
if (overflow == 0) {
1875
while(result == NULL) {
1876
item = PyIter_Next(iter);
1879
if (PyErr_Occurred())
1881
return PyLong_FromLong(i_result);
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)) {
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);
1898
if (result == NULL) {
1905
if (PyFloat_CheckExact(result)) {
1906
double f_result = PyFloat_AS_DOUBLE(result);
1909
while(result == NULL) {
1910
item = PyIter_Next(iter);
1913
if (PyErr_Occurred())
1915
return PyFloat_FromDouble(f_result);
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)
1924
if (PyLong_CheckExact(item)) {
1927
value = PyLong_AsLongAndOverflow(item, &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)
1936
result = PyFloat_FromDouble(f_result);
1937
temp = PyNumber_Add(result, item);
1941
if (result == NULL) {
1950
item = PyIter_Next(iter);
1952
/* error, or end-of-sequence */
1953
if (PyErr_Occurred()) {
1959
temp = PyNumber_Add(result, item);
1970
PyDoc_STRVAR(sum_doc,
1971
"sum(iterable[, start]) -> value\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.");
1979
builtin_isinstance(PyObject *self, PyObject *args)
1985
if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
1988
retval = PyObject_IsInstance(inst, cls);
1991
return PyBool_FromLong(retval);
1994
PyDoc_STRVAR(isinstance_doc,
1995
"isinstance(object, class-or-type-or-tuple) -> bool\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.).");
2004
builtin_issubclass(PyObject *self, PyObject *args)
2010
if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
2013
retval = PyObject_IsSubclass(derived, cls);
2016
return PyBool_FromLong(retval);
2019
PyDoc_STRVAR(issubclass_doc,
2020
"issubclass(C, B) -> bool\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.).");
2029
Py_ssize_t tuplesize;
2030
PyObject *ittuple; /* tuple of iterators */
2034
PyTypeObject PyZip_Type;
2037
zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2041
PyObject *ittuple; /* tuple of iterators */
2043
Py_ssize_t tuplesize = PySequence_Length(args);
2045
if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds))
2048
/* args must be a tuple */
2049
assert(PyTuple_Check(args));
2051
/* obtain iterators */
2052
ittuple = PyTuple_New(tuplesize);
2053
if (ittuple == NULL)
2055
for (i=0; i < tuplesize; ++i) {
2056
PyObject *item = PyTuple_GET_ITEM(args, i);
2057
PyObject *it = PyObject_GetIter(item);
2059
if (PyErr_ExceptionMatches(PyExc_TypeError))
2060
PyErr_Format(PyExc_TypeError,
2061
"zip argument #%zd must support iteration",
2066
PyTuple_SET_ITEM(ittuple, i, it);
2069
/* create a result holder */
2070
result = PyTuple_New(tuplesize);
2071
if (result == NULL) {
2075
for (i=0 ; i < tuplesize ; i++) {
2077
PyTuple_SET_ITEM(result, i, Py_None);
2080
/* create zipobject structure */
2081
lz = (zipobject *)type->tp_alloc(type, 0);
2087
lz->ittuple = ittuple;
2088
lz->tuplesize = tuplesize;
2089
lz->result = result;
2091
return (PyObject *)lz;
2095
zip_dealloc(zipobject *lz)
2097
PyObject_GC_UnTrack(lz);
2098
Py_XDECREF(lz->ittuple);
2099
Py_XDECREF(lz->result);
2100
Py_TYPE(lz)->tp_free(lz);
2104
zip_traverse(zipobject *lz, visitproc visit, void *arg)
2106
Py_VISIT(lz->ittuple);
2107
Py_VISIT(lz->result);
2112
zip_next(zipobject *lz)
2115
Py_ssize_t tuplesize = lz->tuplesize;
2116
PyObject *result = lz->result;
2123
if (Py_REFCNT(result) == 1) {
2125
for (i=0 ; i < tuplesize ; i++) {
2126
it = PyTuple_GET_ITEM(lz->ittuple, i);
2127
item = (*Py_TYPE(it)->tp_iternext)(it);
2132
olditem = PyTuple_GET_ITEM(result, i);
2133
PyTuple_SET_ITEM(result, i, item);
2137
result = PyTuple_New(tuplesize);
2140
for (i=0 ; i < tuplesize ; i++) {
2141
it = PyTuple_GET_ITEM(lz->ittuple, i);
2142
item = (*Py_TYPE(it)->tp_iternext)(it);
2147
PyTuple_SET_ITEM(result, i, item);
2153
PyDoc_STRVAR(zip_doc,
2154
"zip(iter1 [,iter2 [...]]) --> zip object\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.");
2161
PyTypeObject PyZip_Type = {
2162
PyVarObject_HEAD_INIT(&PyType_Type, 0)
2163
"zip", /* tp_name */
2164
sizeof(zipobject), /* tp_basicsize */
2165
0, /* tp_itemsize */
2167
(destructor)zip_dealloc, /* tp_dealloc */
2171
0, /* tp_reserved */
2173
0, /* tp_as_number */
2174
0, /* tp_as_sequence */
2175
0, /* tp_as_mapping */
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 */
2187
0, /* tp_richcompare */
2188
0, /* tp_weaklistoffset */
2189
PyObject_SelfIter, /* tp_iter */
2190
(iternextfunc)zip_next, /* tp_iternext */
2196
0, /* tp_descr_get */
2197
0, /* tp_descr_set */
2198
0, /* tp_dictoffset */
2200
PyType_GenericAlloc, /* tp_alloc */
2201
zip_new, /* tp_new */
2202
PyObject_GC_Del, /* tp_free */
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},
2251
PyDoc_STRVAR(builtin_doc,
2252
"Built-in functions, exceptions, and other objects.\n\
2254
Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2256
static struct PyModuleDef builtinsmodule = {
2257
PyModuleDef_HEAD_INIT,
2260
-1, /* multiple "initialization" just copies the module dict. */
2270
_PyBuiltin_Init(void)
2272
PyObject *mod, *dict, *debug;
2273
mod = PyModule_Create(&builtinsmodule);
2276
dict = PyModule_GetDict(mod);
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).
2285
#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
2287
#define ADD_TO_ALL(OBJECT) (void)0
2290
#define SETBUILTIN(NAME, OBJECT) \
2291
if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
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);
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) {