Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(3)

Delta Between Two Patch Sets: Python/bltinmodule.c

Issue 8256: input() doesn't catch _PyUnicode_AsString() exception; io.StringIO().encoding is None
Left Patch Set: Created 7 years, 6 months ago
Right Patch Set: Created 4 years, 4 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | no next file » | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 /* Built-in functions */ 1 /* Built-in functions */
2 2
3 #include "Python.h" 3 #include "Python.h"
4 #include "Python-ast.h" 4 #include "Python-ast.h"
5 5
6 #include "node.h" 6 #include "node.h"
7 #include "code.h" 7 #include "code.h"
8 8
9 #include "asdl.h" 9 #include "asdl.h"
10 #include "ast.h" 10 #include "ast.h"
(...skipping 14 matching lines...) Expand all
25 const char *Py_FileSystemDefaultEncoding = "mbcs"; 25 const char *Py_FileSystemDefaultEncoding = "mbcs";
26 int Py_HasFileSystemDefaultEncoding = 1; 26 int Py_HasFileSystemDefaultEncoding = 1;
27 #elif defined(__APPLE__) 27 #elif defined(__APPLE__)
28 const char *Py_FileSystemDefaultEncoding = "utf-8"; 28 const char *Py_FileSystemDefaultEncoding = "utf-8";
29 int Py_HasFileSystemDefaultEncoding = 1; 29 int Py_HasFileSystemDefaultEncoding = 1;
30 #else 30 #else
31 const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */ 31 const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */
32 int Py_HasFileSystemDefaultEncoding = 0; 32 int Py_HasFileSystemDefaultEncoding = 0;
33 #endif 33 #endif
34 34
35 _Py_IDENTIFIER(__builtins__);
36 _Py_IDENTIFIER(__dict__);
37 _Py_IDENTIFIER(__prepare__);
38 _Py_IDENTIFIER(__round__);
39 _Py_IDENTIFIER(encoding);
40 _Py_IDENTIFIER(errors);
35 _Py_IDENTIFIER(fileno); 41 _Py_IDENTIFIER(fileno);
36 _Py_IDENTIFIER(flush); 42 _Py_IDENTIFIER(flush);
37 43 _Py_IDENTIFIER(metaclass);
44 _Py_IDENTIFIER(sort);
45 _Py_IDENTIFIER(stdin);
46 _Py_IDENTIFIER(stdout);
47 _Py_IDENTIFIER(stderr);
48
49 #include "clinic/bltinmodule.c.h"
50
51 /* AC: cannot convert yet, waiting for *args support */
38 static PyObject * 52 static PyObject *
39 builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds) 53 builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
40 { 54 {
41 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell; 55 PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell;
42 PyObject *cls = NULL; 56 PyObject *cls = NULL;
43 Py_ssize_t nargs; 57 Py_ssize_t nargs;
44 int isclass; 58 int isclass = 0; /* initialize to prevent gcc warning */
45 _Py_IDENTIFIER(__prepare__);
46 59
47 assert(args != NULL); 60 assert(args != NULL);
48 if (!PyTuple_Check(args)) { 61 if (!PyTuple_Check(args)) {
49 PyErr_SetString(PyExc_TypeError, 62 PyErr_SetString(PyExc_TypeError,
50 "__build_class__: args is not a tuple"); 63 "__build_class__: args is not a tuple");
51 return NULL; 64 return NULL;
52 } 65 }
53 nargs = PyTuple_GET_SIZE(args); 66 nargs = PyTuple_GET_SIZE(args);
54 if (nargs < 2) { 67 if (nargs < 2) {
55 PyErr_SetString(PyExc_TypeError, 68 PyErr_SetString(PyExc_TypeError,
56 "__build_class__: not enough arguments"); 69 "__build_class__: not enough arguments");
57 return NULL; 70 return NULL;
58 } 71 }
59 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ 72 func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
73 if (!PyFunction_Check(func)) {
74 PyErr_SetString(PyExc_TypeError,
75 "__build_class__: func must be a function");
76 return NULL;
77 }
60 name = PyTuple_GET_ITEM(args, 1); 78 name = PyTuple_GET_ITEM(args, 1);
61 if (!PyUnicode_Check(name)) { 79 if (!PyUnicode_Check(name)) {
62 PyErr_SetString(PyExc_TypeError, 80 PyErr_SetString(PyExc_TypeError,
63 "__build_class__: name is not a string"); 81 "__build_class__: name is not a string");
64 return NULL; 82 return NULL;
65 } 83 }
66 bases = PyTuple_GetSlice(args, 2, nargs); 84 bases = PyTuple_GetSlice(args, 2, nargs);
67 if (bases == NULL) 85 if (bases == NULL)
68 return NULL; 86 return NULL;
69 87
70 if (kwds == NULL) { 88 if (kwds == NULL) {
71 meta = NULL; 89 meta = NULL;
72 mkw = NULL; 90 mkw = NULL;
73 } 91 }
74 else { 92 else {
75 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ 93 mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
76 if (mkw == NULL) { 94 if (mkw == NULL) {
77 Py_DECREF(bases); 95 Py_DECREF(bases);
78 return NULL; 96 return NULL;
79 } 97 }
80 meta = PyDict_GetItemString(mkw, "metaclass"); 98 meta = _PyDict_GetItemId(mkw, &PyId_metaclass);
81 if (meta != NULL) { 99 if (meta != NULL) {
82 Py_INCREF(meta); 100 Py_INCREF(meta);
83 if (PyDict_DelItemString(mkw, "metaclass") < 0) { 101 if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) {
84 Py_DECREF(meta); 102 Py_DECREF(meta);
85 Py_DECREF(mkw); 103 Py_DECREF(mkw);
86 Py_DECREF(bases); 104 Py_DECREF(bases);
87 return NULL; 105 return NULL;
88 } 106 }
89 /* metaclass is explicitly given, check if it's indeed a class */ 107 /* metaclass is explicitly given, check if it's indeed a class */
90 isclass = PyType_Check(meta); 108 isclass = PyType_Check(meta);
91 } 109 }
92 } 110 }
93 if (meta == NULL) { 111 if (meta == NULL) {
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
148 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); 166 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
149 Py_DECREF(pargs); 167 Py_DECREF(pargs);
150 Py_DECREF(prep); 168 Py_DECREF(prep);
151 } 169 }
152 if (ns == NULL) { 170 if (ns == NULL) {
153 Py_DECREF(meta); 171 Py_DECREF(meta);
154 Py_XDECREF(mkw); 172 Py_XDECREF(mkw);
155 Py_DECREF(bases); 173 Py_DECREF(bases);
156 return NULL; 174 return NULL;
157 } 175 }
158 cell = PyObject_CallFunctionObjArgs(func, ns, NULL); 176 cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(f unc), ns,
177 NULL, 0, NULL, 0, NULL, 0, NULL,
178 PyFunction_GET_CLOSURE(func));
159 if (cell != NULL) { 179 if (cell != NULL) {
160 PyObject *margs; 180 PyObject *margs;
161 margs = PyTuple_Pack(3, name, bases, ns); 181 margs = PyTuple_Pack(3, name, bases, ns);
162 if (margs != NULL) { 182 if (margs != NULL) {
163 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); 183 cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
164 Py_DECREF(margs); 184 Py_DECREF(margs);
165 } 185 }
166 if (cls != NULL && PyCell_Check(cell)) 186 if (cls != NULL && PyCell_Check(cell))
167 PyCell_Set(cell, cls); 187 PyCell_Set(cell, cls);
168 Py_DECREF(cell); 188 Py_DECREF(cell);
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
205 they are not modified. The locals argument is unused. The fromlist\n\ 225 they are not modified. The locals argument is unused. The fromlist\n\
206 should be a list of names to emulate ``from name import ...'', or an\n\ 226 should be a list of names to emulate ``from name import ...'', or an\n\
207 empty list to emulate ``import name''.\n\ 227 empty list to emulate ``import name''.\n\
208 When importing a module from a package, note that __import__('A.B', ...)\n\ 228 When importing a module from a package, note that __import__('A.B', ...)\n\
209 returns package A when fromlist is empty, but its submodule B when\n\ 229 returns package A when fromlist is empty, but its submodule B when\n\
210 fromlist is not empty. Level is used to determine whether to perform \n\ 230 fromlist is not empty. Level is used to determine whether to perform \n\
211 absolute or relative imports. 0 is absolute while a positive number\n\ 231 absolute or relative imports. 0 is absolute while a positive number\n\
212 is the number of parent directories to search relative to the current module."); 232 is the number of parent directories to search relative to the current module.");
213 233
214 234
215 static PyObject * 235 /*[clinic input]
216 builtin_abs(PyObject *self, PyObject *v) 236 abs as builtin_abs
217 { 237
218 return PyNumber_Absolute(v); 238 x: object
219 } 239 /
220 240
221 PyDoc_STRVAR(abs_doc, 241 Return the absolute value of the argument.
222 "abs(number) -> number\n\ 242 [clinic start generated code]*/
223 \n\ 243
224 Return the absolute value of the argument."); 244 static PyObject *
225 245 builtin_abs(PyModuleDef *module, PyObject *x)
226 static PyObject * 246 /*[clinic end generated code: output=6833047c493ecea2 input=bed4ca14e29c20d1]*/
227 builtin_all(PyObject *self, PyObject *v) 247 {
248 return PyNumber_Absolute(x);
249 }
250
251 /*[clinic input]
252 all as builtin_all
253
254 iterable: object
255 /
256
257 Return True if bool(x) is True for all values x in the iterable.
258
259 If the iterable is empty, return True.
260 [clinic start generated code]*/
261
262 static PyObject *
263 builtin_all(PyModuleDef *module, PyObject *iterable)
264 /*[clinic end generated code: output=089e6d1b7bde27b1 input=1a7c5d1bc3438a21]*/
228 { 265 {
229 PyObject *it, *item; 266 PyObject *it, *item;
230 PyObject *(*iternext)(PyObject *); 267 PyObject *(*iternext)(PyObject *);
231 int cmp; 268 int cmp;
232 269
233 it = PyObject_GetIter(v); 270 it = PyObject_GetIter(iterable);
234 if (it == NULL) 271 if (it == NULL)
235 return NULL; 272 return NULL;
236 iternext = *Py_TYPE(it)->tp_iternext; 273 iternext = *Py_TYPE(it)->tp_iternext;
237 274
238 for (;;) { 275 for (;;) {
239 item = iternext(it); 276 item = iternext(it);
240 if (item == NULL) 277 if (item == NULL)
241 break; 278 break;
242 cmp = PyObject_IsTrue(item); 279 cmp = PyObject_IsTrue(item);
243 Py_DECREF(item); 280 Py_DECREF(item);
244 if (cmp < 0) { 281 if (cmp < 0) {
245 Py_DECREF(it); 282 Py_DECREF(it);
246 return NULL; 283 return NULL;
247 } 284 }
248 if (cmp == 0) { 285 if (cmp == 0) {
249 Py_DECREF(it); 286 Py_DECREF(it);
250 Py_RETURN_FALSE; 287 Py_RETURN_FALSE;
251 } 288 }
252 } 289 }
253 Py_DECREF(it); 290 Py_DECREF(it);
254 if (PyErr_Occurred()) { 291 if (PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_StopIteration)) 292 if (PyErr_ExceptionMatches(PyExc_StopIteration))
256 PyErr_Clear(); 293 PyErr_Clear();
257 else 294 else
258 return NULL; 295 return NULL;
259 } 296 }
260 Py_RETURN_TRUE; 297 Py_RETURN_TRUE;
261 } 298 }
262 299
263 PyDoc_STRVAR(all_doc, 300 /*[clinic input]
264 "all(iterable) -> bool\n\ 301 any as builtin_any
265 \n\ 302
266 Return True if bool(x) is True for all values x in the iterable."); 303 iterable: object
267 304 /
268 static PyObject * 305
269 builtin_any(PyObject *self, PyObject *v) 306 Return True if bool(x) is True for any x in the iterable.
307
308 If the iterable is empty, return False.
309 [clinic start generated code]*/
310
311 static PyObject *
312 builtin_any(PyModuleDef *module, PyObject *iterable)
313 /*[clinic end generated code: output=1be994b2c2307492 input=41d7451c23384f24]*/
270 { 314 {
271 PyObject *it, *item; 315 PyObject *it, *item;
272 PyObject *(*iternext)(PyObject *); 316 PyObject *(*iternext)(PyObject *);
273 int cmp; 317 int cmp;
274 318
275 it = PyObject_GetIter(v); 319 it = PyObject_GetIter(iterable);
276 if (it == NULL) 320 if (it == NULL)
277 return NULL; 321 return NULL;
278 iternext = *Py_TYPE(it)->tp_iternext; 322 iternext = *Py_TYPE(it)->tp_iternext;
279 323
280 for (;;) { 324 for (;;) {
281 item = iternext(it); 325 item = iternext(it);
282 if (item == NULL) 326 if (item == NULL)
283 break; 327 break;
284 cmp = PyObject_IsTrue(item); 328 cmp = PyObject_IsTrue(item);
285 Py_DECREF(item); 329 Py_DECREF(item);
286 if (cmp < 0) { 330 if (cmp < 0) {
287 Py_DECREF(it); 331 Py_DECREF(it);
288 return NULL; 332 return NULL;
289 } 333 }
290 if (cmp == 1) { 334 if (cmp == 1) {
291 Py_DECREF(it); 335 Py_DECREF(it);
292 Py_RETURN_TRUE; 336 Py_RETURN_TRUE;
293 } 337 }
294 } 338 }
295 Py_DECREF(it); 339 Py_DECREF(it);
296 if (PyErr_Occurred()) { 340 if (PyErr_Occurred()) {
297 if (PyErr_ExceptionMatches(PyExc_StopIteration)) 341 if (PyErr_ExceptionMatches(PyExc_StopIteration))
298 PyErr_Clear(); 342 PyErr_Clear();
299 else 343 else
300 return NULL; 344 return NULL;
301 } 345 }
302 Py_RETURN_FALSE; 346 Py_RETURN_FALSE;
303 } 347 }
304 348
305 PyDoc_STRVAR(any_doc, 349 /*[clinic input]
306 "any(iterable) -> bool\n\ 350 ascii as builtin_ascii
307 \n\ 351
308 Return True if bool(x) is True for any x in the iterable."); 352 obj: object
309 353 /
310 static PyObject * 354
311 builtin_ascii(PyObject *self, PyObject *v) 355 Return an ASCII-only representation of an object.
312 { 356
313 return PyObject_ASCII(v); 357 As repr(), return a string containing a printable representation of an
314 } 358 object, but escape the non-ASCII characters in the string returned by
315 359 repr() using \\x, \\u or \\U escapes. This generates a string similar
316 PyDoc_STRVAR(ascii_doc, 360 to that returned by repr() in Python 2.
317 "ascii(object) -> string\n\ 361 [clinic start generated code]*/
318 \n\ 362
319 As repr(), return a string containing a printable representation of an\n\ 363 static PyObject *
320 object, but escape the non-ASCII characters in the string returned by\n\ 364 builtin_ascii(PyModuleDef *module, PyObject *obj)
321 repr() using \\x, \\u or \\U escapes. This generates a string similar\n\ 365 /*[clinic end generated code: output=d4e862c48af2a933 input=4c62732e1b3a3cc9]*/
322 to that returned by repr() in Python 2."); 366 {
323 367 return PyObject_ASCII(obj);
324 368 }
325 static PyObject * 369
326 builtin_bin(PyObject *self, PyObject *v) 370
327 { 371 /*[clinic input]
328 return PyNumber_ToBase(v, 2); 372 bin as builtin_bin
329 } 373
330 374 number: object
331 PyDoc_STRVAR(bin_doc, 375 /
332 "bin(number) -> string\n\ 376
333 \n\ 377 Return the binary representation of an integer.
334 Return the binary representation of an integer."); 378
335 379 >>> bin(2796202)
336 380 '0b1010101010101010101010'
337 static PyObject * 381 [clinic start generated code]*/
338 builtin_callable(PyObject *self, PyObject *v) 382
339 { 383 static PyObject *
340 return PyBool_FromLong((long)PyCallable_Check(v)); 384 builtin_bin(PyModuleDef *module, PyObject *number)
341 } 385 /*[clinic end generated code: output=25ee26c6cf3bbb54 input=53f8a0264bacaf90]*/
342 386 {
343 PyDoc_STRVAR(callable_doc, 387 return PyNumber_ToBase(number, 2);
344 "callable(object) -> bool\n\ 388 }
345 \n\ 389
346 Return whether the object is callable (i.e., some kind of function).\n\ 390
347 Note that classes are callable, as are instances of classes with a\n\ 391 /*[clinic input]
348 __call__() method."); 392 callable as builtin_callable
393
394 obj: object
395 /
396
397 Return whether the object is callable (i.e., some kind of function).
398
399 Note that classes are callable, as are instances of classes with a
400 __call__() method.
401 [clinic start generated code]*/
402
403 static PyObject *
404 builtin_callable(PyModuleDef *module, PyObject *obj)
405 /*[clinic end generated code: output=f4df2ce92364b656 input=1423bab99cc41f58]*/
406 {
407 return PyBool_FromLong((long)PyCallable_Check(obj));
408 }
349 409
350 410
351 typedef struct { 411 typedef struct {
352 PyObject_HEAD 412 PyObject_HEAD
353 PyObject *func; 413 PyObject *func;
354 PyObject *it; 414 PyObject *it;
355 } filterobject; 415 } filterobject;
356 416
357 static PyObject * 417 static PyObject *
358 filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 418 filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
(...skipping 135 matching lines...) Expand 10 before | Expand all | Expand 10 after
494 0, /* tp_descr_get */ 554 0, /* tp_descr_get */
495 0, /* tp_descr_set */ 555 0, /* tp_descr_set */
496 0, /* tp_dictoffset */ 556 0, /* tp_dictoffset */
497 0, /* tp_init */ 557 0, /* tp_init */
498 PyType_GenericAlloc, /* tp_alloc */ 558 PyType_GenericAlloc, /* tp_alloc */
499 filter_new, /* tp_new */ 559 filter_new, /* tp_new */
500 PyObject_GC_Del, /* tp_free */ 560 PyObject_GC_Del, /* tp_free */
501 }; 561 };
502 562
503 563
504 static PyObject * 564 /*[clinic input]
505 builtin_format(PyObject *self, PyObject *args) 565 format as builtin_format
506 { 566
507 PyObject *value; 567 value: object
508 PyObject *format_spec = NULL; 568 format_spec: unicode(c_default="NULL") = ''
509 569 /
510 if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec)) 570
511 return NULL; 571 Return value.__format__(format_spec)
512 572
573 format_spec defaults to the empty string
574 [clinic start generated code]*/
575
576 static PyObject *
577 builtin_format_impl(PyModuleDef *module, PyObject *value,
578 PyObject *format_spec)
579 /*[clinic end generated code: output=4341fd78a5f01764 input=6325e751a1b29b86]*/
580 {
513 return PyObject_Format(value, format_spec); 581 return PyObject_Format(value, format_spec);
514 } 582 }
515 583
516 PyDoc_STRVAR(format_doc, 584 /*[clinic input]
517 "format(value[, format_spec]) -> string\n\ 585 chr as builtin_chr
518 \n\ 586
519 Returns value.__format__(format_spec)\n\ 587 i: int
520 format_spec defaults to \"\""); 588 /
521 589
522 static PyObject * 590 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
523 builtin_chr(PyObject *self, PyObject *args) 591 [clinic start generated code]*/
524 { 592
525 int x; 593 static PyObject *
526 594 builtin_chr_impl(PyModuleDef *module, int i)
527 if (!PyArg_ParseTuple(args, "i:chr", &x)) 595 /*[clinic end generated code: output=67fe4d87e690f373 input=3f604ef45a70750d]*/
528 return NULL; 596 {
529 597 return PyUnicode_FromOrdinal(i);
530 return PyUnicode_FromOrdinal(x); 598 }
531 } 599
532 600
533 PyDoc_STRVAR(chr_doc, 601 static const char *
534 "chr(i) -> Unicode character\n\ 602 source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompil erFlags *cf, Py_buffer *view)
535 \n\ 603 {
536 Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff."); 604 const char *str;
537
538
539 static char *
540 source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf)
541 {
542 char *str;
543 Py_ssize_t size; 605 Py_ssize_t size;
544 606
545 if (PyUnicode_Check(cmd)) { 607 if (PyUnicode_Check(cmd)) {
546 cf->cf_flags |= PyCF_IGNORE_COOKIE; 608 cf->cf_flags |= PyCF_IGNORE_COOKIE;
547 str = PyUnicode_AsUTF8AndSize(cmd, &size); 609 str = PyUnicode_AsUTF8AndSize(cmd, &size);
548 if (str == NULL) 610 if (str == NULL)
549 return NULL; 611 return NULL;
550 } 612 }
551 else if (!PyObject_CheckReadBuffer(cmd)) { 613 else if (PyObject_GetBuffer(cmd, view, PyBUF_SIMPLE) == 0) {
614 str = (const char *)view->buf;
615 size = view->len;
616 }
617 else {
552 PyErr_Format(PyExc_TypeError, 618 PyErr_Format(PyExc_TypeError,
553 "%s() arg 1 must be a %s object", 619 "%s() arg 1 must be a %s object",
554 funcname, what); 620 funcname, what);
555 return NULL; 621 return NULL;
556 } 622 }
557 else if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { 623
558 return NULL; 624 if (strlen(str) != (size_t)size) {
559 } 625 PyErr_SetString(PyExc_ValueError,
560
561 if (strlen(str) != size) {
562 PyErr_SetString(PyExc_TypeError,
563 "source code string cannot contain null bytes"); 626 "source code string cannot contain null bytes");
627 PyBuffer_Release(view);
564 return NULL; 628 return NULL;
565 } 629 }
566 return str; 630 return str;
567 } 631 }
568 632
569 static PyObject * 633 /*[clinic input]
570 builtin_compile(PyObject *self, PyObject *args, PyObject *kwds) 634 compile as builtin_compile
571 { 635
572 char *str; 636 source: object
573 PyObject *filename_obj; 637 filename: object(converter="PyUnicode_FSDecoder")
574 char *filename; 638 mode: str
575 char *startstr; 639 flags: int = 0
576 int mode = -1; 640 dont_inherit: int(c_default="0") = False
577 int dont_inherit = 0; 641 optimize: int = -1
578 int supplied_flags = 0; 642
579 int optimize = -1; 643 Compile source into a code object that can be executed by exec() or eval().
644
645 The source code may represent a Python module, statement or expression.
646 The filename will be used for run-time error messages.
647 The mode must be 'exec' to compile a module, 'single' to compile a
648 single (interactive) statement, or 'eval' to compile an expression.
649 The flags argument, if present, controls which future statements influence
650 the compilation of the code.
651 The dont_inherit argument, if true, stops the compilation inheriting
652 the effects of any future statements in effect in the code calling
653 compile; if absent or false these statements do influence the compilation,
654 in addition to any features explicitly specified.
655 [clinic start generated code]*/
656
657 static PyObject *
658 builtin_compile_impl(PyModuleDef *module, PyObject *source,
659 PyObject *filename, const char *mode, int flags,
660 int dont_inherit, int optimize)
661 /*[clinic end generated code: output=31881762c1bb90c4 input=9d53e8cfb3c86414]*/
662 {
663 Py_buffer view = {NULL, NULL};
664 const char *str;
665 int compile_mode = -1;
580 int is_ast; 666 int is_ast;
581 PyCompilerFlags cf; 667 PyCompilerFlags cf;
582 PyObject *cmd;
583 static char *kwlist[] = {"source", "filename", "mode", "flags",
584 "dont_inherit", "optimize", NULL};
585 int start[] = {Py_file_input, Py_eval_input, Py_single_input}; 668 int start[] = {Py_file_input, Py_eval_input, Py_single_input};
586 PyObject *result; 669 PyObject *result;
587 670
588 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile", kwlist, 671 cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
589 &cmd, 672
590 PyUnicode_FSConverter, &filename_obj, 673 if (flags &
591 &startstr, &supplied_flags,
592 &dont_inherit, &optimize))
593 return NULL;
594
595 filename = PyBytes_AS_STRING(filename_obj);
596 cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8;
597
598 if (supplied_flags &
599 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AS T)) 674 ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AS T))
600 { 675 {
601 PyErr_SetString(PyExc_ValueError, 676 PyErr_SetString(PyExc_ValueError,
602 "compile(): unrecognised flags"); 677 "compile(): unrecognised flags");
603 goto error; 678 goto error;
604 } 679 }
605 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ 680 /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
606 681
607 if (optimize < -1 || optimize > 2) { 682 if (optimize < -1 || optimize > 2) {
608 PyErr_SetString(PyExc_ValueError, 683 PyErr_SetString(PyExc_ValueError,
609 "compile(): invalid optimize value"); 684 "compile(): invalid optimize value");
610 goto error; 685 goto error;
611 } 686 }
612 687
613 if (!dont_inherit) { 688 if (!dont_inherit) {
614 PyEval_MergeCompilerFlags(&cf); 689 PyEval_MergeCompilerFlags(&cf);
615 } 690 }
616 691
617 if (strcmp(startstr, "exec") == 0) 692 if (strcmp(mode, "exec") == 0)
618 mode = 0; 693 compile_mode = 0;
619 else if (strcmp(startstr, "eval") == 0) 694 else if (strcmp(mode, "eval") == 0)
620 mode = 1; 695 compile_mode = 1;
621 else if (strcmp(startstr, "single") == 0) 696 else if (strcmp(mode, "single") == 0)
622 mode = 2; 697 compile_mode = 2;
623 else { 698 else {
624 PyErr_SetString(PyExc_ValueError, 699 PyErr_SetString(PyExc_ValueError,
625 "compile() arg 3 must be 'exec', 'eval' or 'single'"); 700 "compile() mode must be 'exec', 'eval' or 'single'");
626 goto error; 701 goto error;
627 } 702 }
628 703
629 is_ast = PyAST_Check(cmd); 704 is_ast = PyAST_Check(source);
630 if (is_ast == -1) 705 if (is_ast == -1)
631 goto error; 706 goto error;
632 if (is_ast) { 707 if (is_ast) {
633 if (supplied_flags & PyCF_ONLY_AST) { 708 if (flags & PyCF_ONLY_AST) {
634 Py_INCREF(cmd); 709 Py_INCREF(source);
635 result = cmd; 710 result = source;
636 } 711 }
637 else { 712 else {
638 PyArena *arena; 713 PyArena *arena;
639 mod_ty mod; 714 mod_ty mod;
640 715
641 arena = PyArena_New(); 716 arena = PyArena_New();
642 if (arena == NULL) 717 if (arena == NULL)
643 goto error; 718 goto error;
644 mod = PyAST_obj2mod(cmd, arena, mode); 719 mod = PyAST_obj2mod(source, arena, compile_mode);
645 if (mod == NULL) { 720 if (mod == NULL) {
646 PyArena_Free(arena); 721 PyArena_Free(arena);
647 goto error; 722 goto error;
648 } 723 }
649 if (!PyAST_Validate(mod)) { 724 if (!PyAST_Validate(mod)) {
650 PyArena_Free(arena); 725 PyArena_Free(arena);
651 goto error; 726 goto error;
652 } 727 }
653 result = (PyObject*)PyAST_CompileEx(mod, filename, 728 result = (PyObject*)PyAST_CompileObject(mod, filename,
654 &cf, optimize, arena); 729 &cf, optimize, arena);
655 PyArena_Free(arena); 730 PyArena_Free(arena);
656 } 731 }
657 goto finally; 732 goto finally;
658 } 733 }
659 734
660 str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); 735 str = source_as_string(source, "compile", "string, bytes or AST", &cf, &view );
661 if (str == NULL) 736 if (str == NULL)
662 goto error; 737 goto error;
663 738
664 result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize); 739 result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, opt imize);
740 PyBuffer_Release(&view);
665 goto finally; 741 goto finally;
666 742
667 error: 743 error:
668 result = NULL; 744 result = NULL;
669 finally: 745 finally:
670 Py_DECREF(filename_obj); 746 Py_DECREF(filename);
671 return result; 747 return result;
672 } 748 }
673 749
674 PyDoc_STRVAR(compile_doc, 750 /* AC: cannot convert yet, as needs PEP 457 group support in inspect */
675 "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
676 \n\
677 Compile the source string (a Python module, statement or expression)\n\
678 into a code object that can be executed by exec() or eval().\n\
679 The filename will be used for run-time error messages.\n\
680 The mode must be 'exec' to compile a module, 'single' to compile a\n\
681 single (interactive) statement, or 'eval' to compile an expression.\n\
682 The flags argument, if present, controls which future statements influence\n\
683 the compilation of the code.\n\
684 The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
685 the effects of any future statements in effect in the code calling\n\
686 compile; if absent or zero these statements do influence the compilation,\n\
687 in addition to any features explicitly specified.");
688
689 static PyObject * 751 static PyObject *
690 builtin_dir(PyObject *self, PyObject *args) 752 builtin_dir(PyObject *self, PyObject *args)
691 { 753 {
692 PyObject *arg = NULL; 754 PyObject *arg = NULL;
693 755
694 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) 756 if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
695 return NULL; 757 return NULL;
696 return PyObject_Dir(arg); 758 return PyObject_Dir(arg);
697 } 759 }
698 760
699 PyDoc_STRVAR(dir_doc, 761 PyDoc_STRVAR(dir_doc,
700 "dir([object]) -> list of strings\n" 762 "dir([object]) -> list of strings\n"
701 "\n" 763 "\n"
702 "If called without an argument, return the names in the current scope.\n" 764 "If called without an argument, return the names in the current scope.\n"
703 "Else, return an alphabetized list of names comprising (some of) the attributes\ n" 765 "Else, return an alphabetized list of names comprising (some of) the attributes\ n"
704 "of the given object, and of attributes reachable from it.\n" 766 "of the given object, and of attributes reachable from it.\n"
705 "If the object supplies a method named __dir__, it will be used; otherwise\n" 767 "If the object supplies a method named __dir__, it will be used; otherwise\n"
706 "the default dir() logic is used and returns:\n" 768 "the default dir() logic is used and returns:\n"
707 " for a module object: the module's attributes.\n" 769 " for a module object: the module's attributes.\n"
708 " for a class object: its attributes, and recursively the attributes\n" 770 " for a class object: its attributes, and recursively the attributes\n"
709 " of its bases.\n" 771 " of its bases.\n"
710 " for any other object: its attributes, its class's attributes, and\n" 772 " for any other object: its attributes, its class's attributes, and\n"
711 " recursively the attributes of its class's base classes."); 773 " recursively the attributes of its class's base classes.");
712 774
713 static PyObject * 775 /*[clinic input]
714 builtin_divmod(PyObject *self, PyObject *args) 776 divmod as builtin_divmod
715 { 777
716 PyObject *v, *w; 778 x: object
717 779 y: object
718 if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) 780 /
719 return NULL; 781
720 return PyNumber_Divmod(v, w); 782 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
721 } 783 [clinic start generated code]*/
722 784
723 PyDoc_STRVAR(divmod_doc, 785 static PyObject *
724 "divmod(x, y) -> (div, mod)\n\ 786 builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
725 \n\ 787 /*[clinic end generated code: output=9ad0076120ebf9ac input=7fdb15f8a97a5fe7]*/
726 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x."); 788 {
727 789 return PyNumber_Divmod(x, y);
728 790 }
729 static PyObject * 791
730 builtin_eval(PyObject *self, PyObject *args) 792
731 { 793 /*[clinic input]
732 PyObject *cmd, *result, *tmp = NULL; 794 eval as builtin_eval
733 PyObject *globals = Py_None, *locals = Py_None; 795
734 char *str; 796 source: object
797 globals: object = None
798 locals: object = None
799 /
800
801 Evaluate the given source in the context of globals and locals.
802
803 The source may be a string representing a Python expression
804 or a code object as returned by compile().
805 The globals must be a dictionary and locals can be any mapping,
806 defaulting to the current globals and locals.
807 If only globals is given, locals defaults to it.
808 [clinic start generated code]*/
809
810 static PyObject *
811 builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
812 PyObject *locals)
813 /*[clinic end generated code: output=7284501fb7b4d666 input=11ee718a8640e527]*/
814 {
815 PyObject *result, *tmp = NULL;
816 Py_buffer view = {NULL, NULL};
817 const char *str;
735 PyCompilerFlags cf; 818 PyCompilerFlags cf;
736 819
737 if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
738 return NULL;
739 if (locals != Py_None && !PyMapping_Check(locals)) { 820 if (locals != Py_None && !PyMapping_Check(locals)) {
740 PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); 821 PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
741 return NULL; 822 return NULL;
742 } 823 }
743 if (globals != Py_None && !PyDict_Check(globals)) { 824 if (globals != Py_None && !PyDict_Check(globals)) {
744 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? 825 PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
745 "globals must be a real dict; try eval(expr, {}, mapping)" 826 "globals must be a real dict; try eval(expr, {}, mapping)"
746 : "globals must be a dict"); 827 : "globals must be a dict");
747 return NULL; 828 return NULL;
748 } 829 }
749 if (globals == Py_None) { 830 if (globals == Py_None) {
750 globals = PyEval_GetGlobals(); 831 globals = PyEval_GetGlobals();
751 if (locals == Py_None) 832 if (locals == Py_None) {
752 locals = PyEval_GetLocals(); 833 locals = PyEval_GetLocals();
834 if (locals == NULL)
835 return NULL;
836 }
753 } 837 }
754 else if (locals == Py_None) 838 else if (locals == Py_None)
755 locals = globals; 839 locals = globals;
756 840
757 if (globals == NULL || locals == NULL) { 841 if (globals == NULL || locals == NULL) {
758 PyErr_SetString(PyExc_TypeError, 842 PyErr_SetString(PyExc_TypeError,
759 "eval must be given globals and locals " 843 "eval must be given globals and locals "
760 "when called without a frame"); 844 "when called without a frame");
761 return NULL; 845 return NULL;
762 } 846 }
763 847
764 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 848 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
765 if (PyDict_SetItemString(globals, "__builtins__", 849 if (_PyDict_SetItemId(globals, &PyId___builtins__,
766 PyEval_GetBuiltins()) != 0) 850 PyEval_GetBuiltins()) != 0)
767 return NULL; 851 return NULL;
768 } 852 }
769 853
770 if (PyCode_Check(cmd)) { 854 if (PyCode_Check(source)) {
771 if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { 855 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
772 PyErr_SetString(PyExc_TypeError, 856 PyErr_SetString(PyExc_TypeError,
773 "code object passed to eval() may not contain free variables"); 857 "code object passed to eval() may not contain free variables");
774 return NULL; 858 return NULL;
775 } 859 }
776 return PyEval_EvalCode(cmd, globals, locals); 860 return PyEval_EvalCode(source, globals, locals);
777 } 861 }
778 862
779 cf.cf_flags = PyCF_SOURCE_IS_UTF8; 863 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
780 str = source_as_string(cmd, "eval", "string, bytes or code", &cf); 864 str = source_as_string(source, "eval", "string, bytes or code", &cf, &view);
781 if (str == NULL) 865 if (str == NULL)
782 return NULL; 866 return NULL;
783 867
784 while (*str == ' ' || *str == '\t') 868 while (*str == ' ' || *str == '\t')
785 str++; 869 str++;
786 870
787 (void)PyEval_MergeCompilerFlags(&cf); 871 (void)PyEval_MergeCompilerFlags(&cf);
788 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); 872 result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
873 PyBuffer_Release(&view);
789 Py_XDECREF(tmp); 874 Py_XDECREF(tmp);
790 return result; 875 return result;
791 } 876 }
792 877
793 PyDoc_STRVAR(eval_doc, 878 /*[clinic input]
794 "eval(source[, globals[, locals]]) -> value\n\ 879 exec as builtin_exec
795 \n\ 880
796 Evaluate the source in the context of globals and locals.\n\ 881 source: object
797 The source may be a string representing a Python expression\n\ 882 globals: object = None
798 or a code object as returned by compile().\n\ 883 locals: object = None
799 The globals must be a dictionary and locals can be any mapping,\n\ 884 /
800 defaulting to the current globals and locals.\n\ 885
801 If only globals is given, locals defaults to it.\n"); 886 Execute the given source in the context of globals and locals.
802 887
803 static PyObject * 888 The source may be a string representing one or more Python statements
804 builtin_exec(PyObject *self, PyObject *args) 889 or a code object as returned by compile().
890 The globals must be a dictionary and locals can be any mapping,
891 defaulting to the current globals and locals.
892 If only globals is given, locals defaults to it.
893 [clinic start generated code]*/
894
895 static PyObject *
896 builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
897 PyObject *locals)
898 /*[clinic end generated code: output=83d574ef9d5d0b46 input=01ca3e1c01692829]*/
805 { 899 {
806 PyObject *v; 900 PyObject *v;
807 PyObject *prog, *globals = Py_None, *locals = Py_None;
808
809 if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
810 return NULL;
811 901
812 if (globals == Py_None) { 902 if (globals == Py_None) {
813 globals = PyEval_GetGlobals(); 903 globals = PyEval_GetGlobals();
814 if (locals == Py_None) { 904 if (locals == Py_None) {
815 locals = PyEval_GetLocals(); 905 locals = PyEval_GetLocals();
906 if (locals == NULL)
907 return NULL;
816 } 908 }
817 if (!globals || !locals) { 909 if (!globals || !locals) {
818 PyErr_SetString(PyExc_SystemError, 910 PyErr_SetString(PyExc_SystemError,
819 "globals and locals cannot be NULL"); 911 "globals and locals cannot be NULL");
820 return NULL; 912 return NULL;
821 } 913 }
822 } 914 }
823 else if (locals == Py_None) 915 else if (locals == Py_None)
824 locals = globals; 916 locals = globals;
825 917
826 if (!PyDict_Check(globals)) { 918 if (!PyDict_Check(globals)) {
827 PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", 919 PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s ",
828 globals->ob_type->tp_name); 920 globals->ob_type->tp_name);
829 return NULL; 921 return NULL;
830 } 922 }
831 if (!PyMapping_Check(locals)) { 923 if (!PyMapping_Check(locals)) {
832 PyErr_Format(PyExc_TypeError, 924 PyErr_Format(PyExc_TypeError,
833 "arg 3 must be a mapping or None, not %.100s", 925 "locals must be a mapping or None, not %.100s",
834 locals->ob_type->tp_name); 926 locals->ob_type->tp_name);
835 return NULL; 927 return NULL;
836 } 928 }
837 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 929 if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) {
838 if (PyDict_SetItemString(globals, "__builtins__", 930 if (_PyDict_SetItemId(globals, &PyId___builtins__,
839 PyEval_GetBuiltins()) != 0) 931 PyEval_GetBuiltins()) != 0)
840 return NULL; 932 return NULL;
841 } 933 }
842 934
843 if (PyCode_Check(prog)) { 935 if (PyCode_Check(source)) {
844 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { 936 if (PyCode_GetNumFree((PyCodeObject *)source) > 0) {
845 PyErr_SetString(PyExc_TypeError, 937 PyErr_SetString(PyExc_TypeError,
846 "code object passed to exec() may not " 938 "code object passed to exec() may not "
847 "contain free variables"); 939 "contain free variables");
848 return NULL; 940 return NULL;
849 } 941 }
850 v = PyEval_EvalCode(prog, globals, locals); 942 v = PyEval_EvalCode(source, globals, locals);
851 } 943 }
852 else { 944 else {
853 char *str; 945 Py_buffer view = {NULL, NULL};
946 const char *str;
854 PyCompilerFlags cf; 947 PyCompilerFlags cf;
855 cf.cf_flags = PyCF_SOURCE_IS_UTF8; 948 cf.cf_flags = PyCF_SOURCE_IS_UTF8;
856 str = source_as_string(prog, "exec", 949 str = source_as_string(source, "exec",
857 "string, bytes or code", &cf); 950 "string, bytes or code", &cf, &view);
858 if (str == NULL) 951 if (str == NULL)
859 return NULL; 952 return NULL;
860 if (PyEval_MergeCompilerFlags(&cf)) 953 if (PyEval_MergeCompilerFlags(&cf))
861 v = PyRun_StringFlags(str, Py_file_input, globals, 954 v = PyRun_StringFlags(str, Py_file_input, globals,
862 locals, &cf); 955 locals, &cf);
863 else 956 else
864 v = PyRun_String(str, Py_file_input, globals, locals); 957 v = PyRun_String(str, Py_file_input, globals, locals);
958 PyBuffer_Release(&view);
865 } 959 }
866 if (v == NULL) 960 if (v == NULL)
867 return NULL; 961 return NULL;
868 Py_DECREF(v); 962 Py_DECREF(v);
869 Py_RETURN_NONE; 963 Py_RETURN_NONE;
870 } 964 }
871 965
872 PyDoc_STRVAR(exec_doc, 966
873 "exec(object[, globals[, locals]])\n\ 967 /* AC: cannot convert yet, as needs PEP 457 group support in inspect */
874 \n\
875 Read and execute code from an object, which can be a string or a code\n\
876 object.\n\
877 The globals and locals are dictionaries, defaulting to the current\n\
878 globals and locals. If only globals is given, locals defaults to it.");
879
880
881 static PyObject * 968 static PyObject *
882 builtin_getattr(PyObject *self, PyObject *args) 969 builtin_getattr(PyObject *self, PyObject *args)
883 { 970 {
884 PyObject *v, *result, *dflt = NULL; 971 PyObject *v, *result, *dflt = NULL;
885 PyObject *name; 972 PyObject *name;
886 973
887 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) 974 if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
888 return NULL; 975 return NULL;
889 976
890 if (!PyUnicode_Check(name)) { 977 if (!PyUnicode_Check(name)) {
(...skipping 13 matching lines...) Expand all
904 } 991 }
905 992
906 PyDoc_STRVAR(getattr_doc, 993 PyDoc_STRVAR(getattr_doc,
907 "getattr(object, name[, default]) -> value\n\ 994 "getattr(object, name[, default]) -> value\n\
908 \n\ 995 \n\
909 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\ 996 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
910 When a default argument is given, it is returned when the attribute doesn't\n\ 997 When a default argument is given, it is returned when the attribute doesn't\n\
911 exist; without it, an exception is raised in that case."); 998 exist; without it, an exception is raised in that case.");
912 999
913 1000
914 static PyObject * 1001 /*[clinic input]
915 builtin_globals(PyObject *self) 1002 globals as builtin_globals
1003
1004 Return the dictionary containing the current scope's global variables.
1005
1006 NOTE: Updates to this dictionary *will* affect name lookups in the current
1007 global scope and vice-versa.
1008 [clinic start generated code]*/
1009
1010 static PyObject *
1011 builtin_globals_impl(PyModuleDef *module)
1012 /*[clinic end generated code: output=4958645e96dd8138 input=9327576f92bb48ba]*/
916 { 1013 {
917 PyObject *d; 1014 PyObject *d;
918 1015
919 d = PyEval_GetGlobals(); 1016 d = PyEval_GetGlobals();
920 Py_XINCREF(d); 1017 Py_XINCREF(d);
921 return d; 1018 return d;
922 } 1019 }
923 1020
924 PyDoc_STRVAR(globals_doc, 1021
925 "globals() -> dictionary\n\ 1022 /*[clinic input]
926 \n\ 1023 hasattr as builtin_hasattr
927 Return the dictionary containing the current scope's global variables."); 1024
928 1025 obj: object
929 1026 name: object
930 static PyObject * 1027 /
931 builtin_hasattr(PyObject *self, PyObject *args) 1028
1029 Return whether the object has an attribute with the given name.
1030
1031 This is done by calling getattr(obj, name) and catching AttributeError.
1032 [clinic start generated code]*/
1033
1034 static PyObject *
1035 builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
1036 /*[clinic end generated code: output=81154fdd63634696 input=0faec9787d979542]*/
932 { 1037 {
933 PyObject *v; 1038 PyObject *v;
934 PyObject *name; 1039
935
936 if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
937 return NULL;
938 if (!PyUnicode_Check(name)) { 1040 if (!PyUnicode_Check(name)) {
939 PyErr_SetString(PyExc_TypeError, 1041 PyErr_SetString(PyExc_TypeError,
940 "hasattr(): attribute name must be string"); 1042 "hasattr(): attribute name must be string");
941 return NULL; 1043 return NULL;
942 } 1044 }
943 v = PyObject_GetAttr(v, name); 1045 v = PyObject_GetAttr(obj, name);
944 if (v == NULL) { 1046 if (v == NULL) {
945 if (PyErr_ExceptionMatches(PyExc_AttributeError)) { 1047 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
946 PyErr_Clear(); 1048 PyErr_Clear();
947 Py_RETURN_FALSE; 1049 Py_RETURN_FALSE;
948 } 1050 }
949 return NULL; 1051 return NULL;
950 } 1052 }
951 Py_DECREF(v); 1053 Py_DECREF(v);
952 Py_RETURN_TRUE; 1054 Py_RETURN_TRUE;
953 } 1055 }
954 1056
955 PyDoc_STRVAR(hasattr_doc, 1057
956 "hasattr(object, name) -> bool\n\ 1058 /* AC: gdb's integration with CPython relies on builtin_id having
957 \n\ 1059 * the *exact* parameter names of "self" and "v", so we ensure we
958 Return whether the object has an attribute with the given name.\n\ 1060 * preserve those name rather than using the AC defaults.
959 (This is done by calling getattr(object, name) and catching AttributeError.)"); 1061 */
960 1062 /*[clinic input]
961 1063 id as builtin_id
962 static PyObject * 1064
963 builtin_id(PyObject *self, PyObject *v) 1065 self: self(type="PyModuleDef *")
1066 obj as v: object
1067 /
1068
1069 Return the identity of an object.
1070
1071 This is guaranteed to be unique among simultaneously existing objects.
1072 (CPython uses the object's memory address.)
1073 [clinic start generated code]*/
1074
1075 static PyObject *
1076 builtin_id(PyModuleDef *self, PyObject *v)
1077 /*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
964 { 1078 {
965 return PyLong_FromVoidPtr(v); 1079 return PyLong_FromVoidPtr(v);
966 } 1080 }
967
968 PyDoc_STRVAR(id_doc,
969 "id(object) -> integer\n\
970 \n\
971 Return the identity of an object. This is guaranteed to be unique among\n\
972 simultaneously existing objects. (Hint: it's the object's memory address.)");
973 1081
974 1082
975 /* map object ************************************************************/ 1083 /* map object ************************************************************/
976 1084
977 typedef struct { 1085 typedef struct {
978 PyObject_HEAD 1086 PyObject_HEAD
979 PyObject *iters; 1087 PyObject *iters;
980 PyObject *func; 1088 PyObject *func;
981 } mapobject; 1089 } mapobject;
982 1090
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
1043 } 1151 }
1044 1152
1045 static PyObject * 1153 static PyObject *
1046 map_next(mapobject *lz) 1154 map_next(mapobject *lz)
1047 { 1155 {
1048 PyObject *val; 1156 PyObject *val;
1049 PyObject *argtuple; 1157 PyObject *argtuple;
1050 PyObject *result; 1158 PyObject *result;
1051 Py_ssize_t numargs, i; 1159 Py_ssize_t numargs, i;
1052 1160
1053 numargs = PyTuple_Size(lz->iters); 1161 numargs = PyTuple_GET_SIZE(lz->iters);
1054 argtuple = PyTuple_New(numargs); 1162 argtuple = PyTuple_New(numargs);
1055 if (argtuple == NULL) 1163 if (argtuple == NULL)
1056 return NULL; 1164 return NULL;
1057 1165
1058 for (i=0 ; i<numargs ; i++) { 1166 for (i=0 ; i<numargs ; i++) {
1059 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i)); 1167 PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
1168 val = Py_TYPE(it)->tp_iternext(it);
1060 if (val == NULL) { 1169 if (val == NULL) {
1061 Py_DECREF(argtuple); 1170 Py_DECREF(argtuple);
1062 return NULL; 1171 return NULL;
1063 } 1172 }
1064 PyTuple_SET_ITEM(argtuple, i, val); 1173 PyTuple_SET_ITEM(argtuple, i, val);
1065 } 1174 }
1066 result = PyObject_Call(lz->func, argtuple, NULL); 1175 result = PyObject_Call(lz->func, argtuple, NULL);
1067 Py_DECREF(argtuple); 1176 Py_DECREF(argtuple);
1068 return result; 1177 return result;
1069 } 1178 }
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
1136 0, /* tp_dict */ 1245 0, /* tp_dict */
1137 0, /* tp_descr_get */ 1246 0, /* tp_descr_get */
1138 0, /* tp_descr_set */ 1247 0, /* tp_descr_set */
1139 0, /* tp_dictoffset */ 1248 0, /* tp_dictoffset */
1140 0, /* tp_init */ 1249 0, /* tp_init */
1141 PyType_GenericAlloc, /* tp_alloc */ 1250 PyType_GenericAlloc, /* tp_alloc */
1142 map_new, /* tp_new */ 1251 map_new, /* tp_new */
1143 PyObject_GC_Del, /* tp_free */ 1252 PyObject_GC_Del, /* tp_free */
1144 }; 1253 };
1145 1254
1255
1256 /* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1146 static PyObject * 1257 static PyObject *
1147 builtin_next(PyObject *self, PyObject *args) 1258 builtin_next(PyObject *self, PyObject *args)
1148 { 1259 {
1149 PyObject *it, *res; 1260 PyObject *it, *res;
1150 PyObject *def = NULL; 1261 PyObject *def = NULL;
1151 1262
1152 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) 1263 if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
1153 return NULL; 1264 return NULL;
1154 if (!PyIter_Check(it)) { 1265 if (!PyIter_Check(it)) {
1155 PyErr_Format(PyExc_TypeError, 1266 PyErr_Format(PyExc_TypeError,
(...skipping 21 matching lines...) Expand all
1177 } 1288 }
1178 } 1289 }
1179 1290
1180 PyDoc_STRVAR(next_doc, 1291 PyDoc_STRVAR(next_doc,
1181 "next(iterator[, default])\n\ 1292 "next(iterator[, default])\n\
1182 \n\ 1293 \n\
1183 Return the next item from the iterator. If default is given and the iterator\n\ 1294 Return the next item from the iterator. If default is given and the iterator\n\
1184 is exhausted, it is returned instead of raising StopIteration."); 1295 is exhausted, it is returned instead of raising StopIteration.");
1185 1296
1186 1297
1187 static PyObject * 1298 /*[clinic input]
1188 builtin_setattr(PyObject *self, PyObject *args) 1299 setattr as builtin_setattr
1189 { 1300
1190 PyObject *v; 1301 obj: object
1191 PyObject *name; 1302 name: object
1192 PyObject *value; 1303 value: object
1193 1304 /
1194 if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) 1305
1195 return NULL; 1306 Sets the named attribute on the given object to the specified value.
1196 if (PyObject_SetAttr(v, name, value) != 0) 1307
1308 setattr(x, 'y', v) is equivalent to ``x.y = v''
1309 [clinic start generated code]*/
1310
1311 static PyObject *
1312 builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name,
1313 PyObject *value)
1314 /*[clinic end generated code: output=d881c655c0f7e34f input=bd2b7ca6875a1899]*/
1315 {
1316 if (PyObject_SetAttr(obj, name, value) != 0)
1197 return NULL; 1317 return NULL;
1198 Py_INCREF(Py_None); 1318 Py_INCREF(Py_None);
1199 return Py_None; 1319 return Py_None;
1200 } 1320 }
1201 1321
1202 PyDoc_STRVAR(setattr_doc, 1322
1203 "setattr(object, name, value)\n\ 1323 /*[clinic input]
1204 \n\ 1324 delattr as builtin_delattr
1205 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\ 1325
1206 ``x.y = v''."); 1326 obj: object
1207 1327 name: object
1208 1328 /
1209 static PyObject * 1329
1210 builtin_delattr(PyObject *self, PyObject *args) 1330 Deletes the named attribute from the given object.
1211 { 1331
1212 PyObject *v; 1332 delattr(x, 'y') is equivalent to ``del x.y''
1213 PyObject *name; 1333 [clinic start generated code]*/
1214 1334
1215 if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) 1335 static PyObject *
1216 return NULL; 1336 builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
1217 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) 1337 /*[clinic end generated code: output=ef653e698a0b4187 input=db16685d6b4b9410]*/
1338 {
1339 if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
1218 return NULL; 1340 return NULL;
1219 Py_INCREF(Py_None); 1341 Py_INCREF(Py_None);
1220 return Py_None; 1342 return Py_None;
1221 } 1343 }
1222 1344
1223 PyDoc_STRVAR(delattr_doc, 1345
1224 "delattr(object, name)\n\ 1346 /*[clinic input]
1225 \n\ 1347 hash as builtin_hash
1226 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\ 1348
1227 ``del x.y''."); 1349 obj: object
1228 1350 /
1229 1351
1230 static PyObject * 1352 Return the hash value for the given object.
1231 builtin_hash(PyObject *self, PyObject *v) 1353
1354 Two objects that compare equal must also have the same hash value, but the
1355 reverse is not necessarily true.
1356 [clinic start generated code]*/
1357
1358 static PyObject *
1359 builtin_hash(PyModuleDef *module, PyObject *obj)
1360 /*[clinic end generated code: output=1f32ff154c1f751a input=58c48be822bf9c54]*/
1232 { 1361 {
1233 Py_hash_t x; 1362 Py_hash_t x;
1234 1363
1235 x = PyObject_Hash(v); 1364 x = PyObject_Hash(obj);
1236 if (x == -1) 1365 if (x == -1)
1237 return NULL; 1366 return NULL;
1238 return PyLong_FromSsize_t(x); 1367 return PyLong_FromSsize_t(x);
1239 } 1368 }
1240 1369
1241 PyDoc_STRVAR(hash_doc, 1370
1242 "hash(object) -> integer\n\ 1371 /*[clinic input]
1243 \n\ 1372 hex as builtin_hex
1244 Return a hash value for the object. Two objects with the same value have\n\ 1373
1245 the same hash value. The reverse is not necessarily true, but likely."); 1374 number: object
1246 1375 /
1247 1376
1248 static PyObject * 1377 Return the hexadecimal representation of an integer.
1249 builtin_hex(PyObject *self, PyObject *v) 1378
1250 { 1379 >>> hex(12648430)
1251 return PyNumber_ToBase(v, 16); 1380 '0xc0ffee'
1252 } 1381 [clinic start generated code]*/
1253 1382
1254 PyDoc_STRVAR(hex_doc, 1383 static PyObject *
1255 "hex(number) -> string\n\ 1384 builtin_hex(PyModuleDef *module, PyObject *number)
1256 \n\ 1385 /*[clinic end generated code: output=618489ce3cbc5858 input=e645aff5fc7d540e]*/
1257 Return the hexadecimal representation of an integer."); 1386 {
1258 1387 return PyNumber_ToBase(number, 16);
1259 1388 }
1389
1390
1391 /* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1260 static PyObject * 1392 static PyObject *
1261 builtin_iter(PyObject *self, PyObject *args) 1393 builtin_iter(PyObject *self, PyObject *args)
1262 { 1394 {
1263 PyObject *v, *w = NULL; 1395 PyObject *v, *w = NULL;
1264 1396
1265 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) 1397 if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
1266 return NULL; 1398 return NULL;
1267 if (w == NULL) 1399 if (w == NULL)
1268 return PyObject_GetIter(v); 1400 return PyObject_GetIter(v);
1269 if (!PyCallable_Check(v)) { 1401 if (!PyCallable_Check(v)) {
1270 PyErr_SetString(PyExc_TypeError, 1402 PyErr_SetString(PyExc_TypeError,
1271 "iter(v, w): v must be callable"); 1403 "iter(v, w): v must be callable");
1272 return NULL; 1404 return NULL;
1273 } 1405 }
1274 return PyCallIter_New(v, w); 1406 return PyCallIter_New(v, w);
1275 } 1407 }
1276 1408
1277 PyDoc_STRVAR(iter_doc, 1409 PyDoc_STRVAR(iter_doc,
1278 "iter(iterable) -> iterator\n\ 1410 "iter(iterable) -> iterator\n\
1279 iter(callable, sentinel) -> iterator\n\ 1411 iter(callable, sentinel) -> iterator\n\
1280 \n\ 1412 \n\
1281 Get an iterator from an object. In the first form, the argument must\n\ 1413 Get an iterator from an object. In the first form, the argument must\n\
1282 supply its own iterator, or be a sequence.\n\ 1414 supply its own iterator, or be a sequence.\n\
1283 In the second form, the callable is called until it returns the sentinel."); 1415 In the second form, the callable is called until it returns the sentinel.");
1284 1416
1285 1417
1286 static PyObject * 1418 /*[clinic input]
1287 builtin_len(PyObject *self, PyObject *v) 1419 len as builtin_len
1420
1421 obj: object
1422 /
1423
1424 Return the number of items in a container.
1425 [clinic start generated code]*/
1426
1427 static PyObject *
1428 builtin_len(PyModuleDef *module, PyObject *obj)
1429 /*[clinic end generated code: output=8e5837b6f81d915b input=bc55598da9e9c9b5]*/
1288 { 1430 {
1289 Py_ssize_t res; 1431 Py_ssize_t res;
1290 1432
1291 res = PyObject_Size(v); 1433 res = PyObject_Size(obj);
1292 if (res < 0 && PyErr_Occurred()) 1434 if (res < 0 && PyErr_Occurred())
1293 return NULL; 1435 return NULL;
1294 return PyLong_FromSsize_t(res); 1436 return PyLong_FromSsize_t(res);
1295 } 1437 }
1296 1438
1297 PyDoc_STRVAR(len_doc, 1439
1298 "len(object) -> integer\n\ 1440 /*[clinic input]
1299 \n\ 1441 locals as builtin_locals
1300 Return the number of items of a sequence or mapping."); 1442
1301 1443 Return a dictionary containing the current scope's local variables.
1302 1444
1303 static PyObject * 1445 NOTE: Whether or not updates to this dictionary will affect name lookups in
1304 builtin_locals(PyObject *self) 1446 the local scope and vice-versa is *implementation dependent* and not
1447 covered by any backwards compatibility guarantees.
1448 [clinic start generated code]*/
1449
1450 static PyObject *
1451 builtin_locals_impl(PyModuleDef *module)
1452 /*[clinic end generated code: output=8b5a41f12e19d13a input=7874018d478d5c4b]*/
1305 { 1453 {
1306 PyObject *d; 1454 PyObject *d;
1307 1455
1308 d = PyEval_GetLocals(); 1456 d = PyEval_GetLocals();
1309 Py_XINCREF(d); 1457 Py_XINCREF(d);
1310 return d; 1458 return d;
1311 } 1459 }
1312 1460
1313 PyDoc_STRVAR(locals_doc,
1314 "locals() -> dictionary\n\
1315 \n\
1316 Update and return a dictionary containing the current scope's local variables.") ;
1317
1318 1461
1319 static PyObject * 1462 static PyObject *
1320 min_max(PyObject *args, PyObject *kwds, int op) 1463 min_max(PyObject *args, PyObject *kwds, int op)
1321 { 1464 {
1322 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; 1465 PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
1466 PyObject *emptytuple, *defaultval = NULL;
1467 static char *kwlist[] = {"key", "default", NULL};
1323 const char *name = op == Py_LT ? "min" : "max"; 1468 const char *name = op == Py_LT ? "min" : "max";
1324 1469 const int positional = PyTuple_Size(args) > 1;
1325 if (PyTuple_Size(args) > 1) 1470 int ret;
1471
1472 if (positional)
1326 v = args; 1473 v = args;
1327 else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) 1474 else if (!PyArg_UnpackTuple(args, name, 1, 1, &v))
1328 return NULL; 1475 return NULL;
1329 1476
1330 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { 1477 emptytuple = PyTuple_New(0);
1331 keyfunc = PyDict_GetItemString(kwds, "key"); 1478 if (emptytuple == NULL)
1332 if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { 1479 return NULL;
1333 PyErr_Format(PyExc_TypeError, 1480 ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist,
1334 "%s() got an unexpected keyword argument", name); 1481 &keyfunc, &defaultval);
1335 return NULL; 1482 Py_DECREF(emptytuple);
1336 } 1483 if (!ret)
1337 Py_INCREF(keyfunc); 1484 return NULL;
1485
1486 if (positional && defaultval != NULL) {
1487 PyErr_Format(PyExc_TypeError,
1488 "Cannot specify a default for %s() with multiple "
1489 "positional arguments", name);
1490 return NULL;
1338 } 1491 }
1339 1492
1340 it = PyObject_GetIter(v); 1493 it = PyObject_GetIter(v);
1341 if (it == NULL) { 1494 if (it == NULL) {
1342 Py_XDECREF(keyfunc);
1343 return NULL; 1495 return NULL;
1344 } 1496 }
1345 1497
1346 maxitem = NULL; /* the result */ 1498 maxitem = NULL; /* the result */
1347 maxval = NULL; /* the value associated with the result */ 1499 maxval = NULL; /* the value associated with the result */
1348 while (( item = PyIter_Next(it) )) { 1500 while (( item = PyIter_Next(it) )) {
1349 /* get the value from the key function */ 1501 /* get the value from the key function */
1350 if (keyfunc != NULL) { 1502 if (keyfunc != NULL) {
1351 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); 1503 val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
1352 if (val == NULL) 1504 if (val == NULL)
(...skipping 23 matching lines...) Expand all
1376 } 1528 }
1377 else { 1529 else {
1378 Py_DECREF(item); 1530 Py_DECREF(item);
1379 Py_DECREF(val); 1531 Py_DECREF(val);
1380 } 1532 }
1381 } 1533 }
1382 } 1534 }
1383 if (PyErr_Occurred()) 1535 if (PyErr_Occurred())
1384 goto Fail_it; 1536 goto Fail_it;
1385 if (maxval == NULL) { 1537 if (maxval == NULL) {
1386 PyErr_Format(PyExc_ValueError,
1387 "%s() arg is an empty sequence", name);
1388 assert(maxitem == NULL); 1538 assert(maxitem == NULL);
1539 if (defaultval != NULL) {
1540 Py_INCREF(defaultval);
1541 maxitem = defaultval;
1542 } else {
1543 PyErr_Format(PyExc_ValueError,
1544 "%s() arg is an empty sequence", name);
1545 }
1389 } 1546 }
1390 else 1547 else
1391 Py_DECREF(maxval); 1548 Py_DECREF(maxval);
1392 Py_DECREF(it); 1549 Py_DECREF(it);
1393 Py_XDECREF(keyfunc);
1394 return maxitem; 1550 return maxitem;
1395 1551
1396 Fail_it_item_and_val: 1552 Fail_it_item_and_val:
1397 Py_DECREF(val); 1553 Py_DECREF(val);
1398 Fail_it_item: 1554 Fail_it_item:
1399 Py_DECREF(item); 1555 Py_DECREF(item);
1400 Fail_it: 1556 Fail_it:
1401 Py_XDECREF(maxval); 1557 Py_XDECREF(maxval);
1402 Py_XDECREF(maxitem); 1558 Py_XDECREF(maxitem);
1403 Py_DECREF(it); 1559 Py_DECREF(it);
1404 Py_XDECREF(keyfunc);
1405 return NULL; 1560 return NULL;
1406 } 1561 }
1407 1562
1563 /* AC: cannot convert yet, waiting for *args support */
1408 static PyObject * 1564 static PyObject *
1409 builtin_min(PyObject *self, PyObject *args, PyObject *kwds) 1565 builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
1410 { 1566 {
1411 return min_max(args, kwds, Py_LT); 1567 return min_max(args, kwds, Py_LT);
1412 } 1568 }
1413 1569
1414 PyDoc_STRVAR(min_doc, 1570 PyDoc_STRVAR(min_doc,
1415 "min(iterable[, key=func]) -> value\n\ 1571 "min(iterable, *[, default=obj, key=func]) -> value\n\
1416 min(a, b, c, ...[, key=func]) -> value\n\ 1572 min(arg1, arg2, *args, *[, key=func]) -> value\n\
1417 \n\ 1573 \n\
1418 With a single iterable argument, return its smallest item.\n\ 1574 With a single iterable argument, return its smallest item. The\n\
1575 default keyword-only argument specifies an object to return if\n\
1576 the provided iterable is empty.\n\
1419 With two or more arguments, return the smallest argument."); 1577 With two or more arguments, return the smallest argument.");
1420 1578
1421 1579
1580 /* AC: cannot convert yet, waiting for *args support */
1422 static PyObject * 1581 static PyObject *
1423 builtin_max(PyObject *self, PyObject *args, PyObject *kwds) 1582 builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
1424 { 1583 {
1425 return min_max(args, kwds, Py_GT); 1584 return min_max(args, kwds, Py_GT);
1426 } 1585 }
1427 1586
1428 PyDoc_STRVAR(max_doc, 1587 PyDoc_STRVAR(max_doc,
1429 "max(iterable[, key=func]) -> value\n\ 1588 "max(iterable, *[, default=obj, key=func]) -> value\n\
1430 max(a, b, c, ...[, key=func]) -> value\n\ 1589 max(arg1, arg2, *args, *[, key=func]) -> value\n\
1431 \n\ 1590 \n\
1432 With a single iterable argument, return its largest item.\n\ 1591 With a single iterable argument, return its biggest item. The\n\
1592 default keyword-only argument specifies an object to return if\n\
1593 the provided iterable is empty.\n\
1433 With two or more arguments, return the largest argument."); 1594 With two or more arguments, return the largest argument.");
1434 1595
1435 1596
1436 static PyObject * 1597 /*[clinic input]
1437 builtin_oct(PyObject *self, PyObject *v) 1598 oct as builtin_oct
1438 { 1599
1439 return PyNumber_ToBase(v, 8); 1600 number: object
1440 } 1601 /
1441 1602
1442 PyDoc_STRVAR(oct_doc, 1603 Return the octal representation of an integer.
1443 "oct(number) -> string\n\ 1604
1444 \n\ 1605 >>> oct(342391)
1445 Return the octal representation of an integer."); 1606 '0o1234567'
1446 1607 [clinic start generated code]*/
1447 1608
1448 static PyObject * 1609 static PyObject *
1449 builtin_ord(PyObject *self, PyObject* obj) 1610 builtin_oct(PyModuleDef *module, PyObject *number)
1611 /*[clinic end generated code: output=18f701bc6d8f804a input=ad6b274af4016c72]*/
1612 {
1613 return PyNumber_ToBase(number, 8);
1614 }
1615
1616
1617 /*[clinic input]
1618 ord as builtin_ord
1619
1620 c: object
1621 /
1622
1623 Return the Unicode code point for a one-character string.
1624 [clinic start generated code]*/
1625
1626 static PyObject *
1627 builtin_ord(PyModuleDef *module, PyObject *c)
1628 /*[clinic end generated code: output=04fd27272d9462f6 input=3064e5d6203ad012]*/
1450 { 1629 {
1451 long ord; 1630 long ord;
1452 Py_ssize_t size; 1631 Py_ssize_t size;
1453 1632
1454 if (PyBytes_Check(obj)) { 1633 if (PyBytes_Check(c)) {
1455 size = PyBytes_GET_SIZE(obj); 1634 size = PyBytes_GET_SIZE(c);
1456 if (size == 1) { 1635 if (size == 1) {
1457 ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); 1636 ord = (long)((unsigned char)*PyBytes_AS_STRING(c));
1458 return PyLong_FromLong(ord); 1637 return PyLong_FromLong(ord);
1459 } 1638 }
1460 } 1639 }
1461 else if (PyUnicode_Check(obj)) { 1640 else if (PyUnicode_Check(c)) {
1462 if (PyUnicode_READY(obj) == -1) 1641 if (PyUnicode_READY(c) == -1)
1463 return NULL; 1642 return NULL;
1464 size = PyUnicode_GET_LENGTH(obj); 1643 size = PyUnicode_GET_LENGTH(c);
1465 if (size == 1) { 1644 if (size == 1) {
1466 ord = (long)PyUnicode_READ_CHAR(obj, 0); 1645 ord = (long)PyUnicode_READ_CHAR(c, 0);
1467 return PyLong_FromLong(ord); 1646 return PyLong_FromLong(ord);
1468 } 1647 }
1469 } 1648 }
1470 else if (PyByteArray_Check(obj)) { 1649 else if (PyByteArray_Check(c)) {
1471 /* XXX Hopefully this is temporary */ 1650 /* XXX Hopefully this is temporary */
1472 size = PyByteArray_GET_SIZE(obj); 1651 size = PyByteArray_GET_SIZE(c);
1473 if (size == 1) { 1652 if (size == 1) {
1474 ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); 1653 ord = (long)((unsigned char)*PyByteArray_AS_STRING(c));
1475 return PyLong_FromLong(ord); 1654 return PyLong_FromLong(ord);
1476 } 1655 }
1477 } 1656 }
1478 else { 1657 else {
1479 PyErr_Format(PyExc_TypeError, 1658 PyErr_Format(PyExc_TypeError,
1480 "ord() expected string of length 1, but " \ 1659 "ord() expected string of length 1, but " \
1481 "%.200s found", obj->ob_type->tp_name); 1660 "%.200s found", c->ob_type->tp_name);
1482 return NULL; 1661 return NULL;
1483 } 1662 }
1484 1663
1485 PyErr_Format(PyExc_TypeError, 1664 PyErr_Format(PyExc_TypeError,
1486 "ord() expected a character, " 1665 "ord() expected a character, "
1487 "but string of length %zd found", 1666 "but string of length %zd found",
1488 size); 1667 size);
1489 return NULL; 1668 return NULL;
1490 } 1669 }
1491 1670
1492 PyDoc_VAR(ord_doc) = PyDoc_STR( 1671
1493 "ord(c) -> integer\n\ 1672 /*[clinic input]
1494 \n\ 1673 pow as builtin_pow
1495 Return the integer ordinal of a one-character string." 1674
1496 ); 1675 x: object
1497 1676 y: object
1498 1677 z: object = None
1499 static PyObject * 1678 /
1500 builtin_pow(PyObject *self, PyObject *args) 1679
1501 { 1680 Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
1502 PyObject *v, *w, *z = Py_None; 1681
1503 1682 Some types, such as ints, are able to use a more efficient algorithm when
1504 if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) 1683 invoked using the three argument form.
1505 return NULL; 1684 [clinic start generated code]*/
1506 return PyNumber_Power(v, w, z); 1685
1507 } 1686 static PyObject *
1508 1687 builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
1509 PyDoc_STRVAR(pow_doc, 1688 /*[clinic end generated code: output=1fba268adba9b45f input=653d57d38d41fc07]*/
1510 "pow(x, y[, z]) -> number\n\ 1689 {
1511 \n\ 1690 return PyNumber_Power(x, y, z);
1512 With two arguments, equivalent to x**y. With three arguments,\n\ 1691 }
1513 equivalent to (x**y) % z, but may be more efficient (e.g. for longs)."); 1692
1514 1693
1515 1694 /* AC: cannot convert yet, waiting for *args support */
1516
1517 static PyObject * 1695 static PyObject *
1518 builtin_print(PyObject *self, PyObject *args, PyObject *kwds) 1696 builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
1519 { 1697 {
1520 static char *kwlist[] = {"sep", "end", "file", "flush", 0}; 1698 static char *kwlist[] = {"sep", "end", "file", "flush", 0};
1521 static PyObject *dummy_args; 1699 static PyObject *dummy_args;
1522 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL; 1700 PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL;
1523 int i, err; 1701 int i, err;
1524 1702
1525 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0))) 1703 if (dummy_args == NULL && !(dummy_args = PyTuple_New(0)))
1526 return NULL; 1704 return NULL;
1527 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print", 1705 if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOOO:print",
1528 kwlist, &sep, &end, &file, &flush)) 1706 kwlist, &sep, &end, &file, &flush))
1529 return NULL; 1707 return NULL;
1530 if (file == NULL || file == Py_None) { 1708 if (file == NULL || file == Py_None) {
1531 file = PySys_GetObject("stdout"); 1709 file = _PySys_GetObjectId(&PyId_stdout);
1710 if (file == NULL) {
1711 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1712 return NULL;
1713 }
1714
1532 /* sys.stdout may be None when FILE* stdout isn't connected */ 1715 /* sys.stdout may be None when FILE* stdout isn't connected */
1533 if (file == Py_None) 1716 if (file == Py_None)
1534 Py_RETURN_NONE; 1717 Py_RETURN_NONE;
1535 } 1718 }
1536 1719
1537 if (sep == Py_None) { 1720 if (sep == Py_None) {
1538 sep = NULL; 1721 sep = NULL;
1539 } 1722 }
1540 else if (sep && !PyUnicode_Check(sep)) { 1723 else if (sep && !PyUnicode_Check(sep)) {
1541 PyErr_Format(PyExc_TypeError, 1724 PyErr_Format(PyExc_TypeError,
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
1575 err = PyFile_WriteObject(end, file, Py_PRINT_RAW); 1758 err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
1576 if (err) 1759 if (err)
1577 return NULL; 1760 return NULL;
1578 1761
1579 if (flush != NULL) { 1762 if (flush != NULL) {
1580 PyObject *tmp; 1763 PyObject *tmp;
1581 int do_flush = PyObject_IsTrue(flush); 1764 int do_flush = PyObject_IsTrue(flush);
1582 if (do_flush == -1) 1765 if (do_flush == -1)
1583 return NULL; 1766 return NULL;
1584 else if (do_flush) { 1767 else if (do_flush) {
1585 tmp = PyObject_CallMethod(file, "flush", ""); 1768 tmp = _PyObject_CallMethodId(file, &PyId_flush, "");
1586 if (tmp == NULL) 1769 if (tmp == NULL)
1587 return NULL; 1770 return NULL;
1588 else 1771 else
1589 Py_DECREF(tmp); 1772 Py_DECREF(tmp);
1590 } 1773 }
1591 } 1774 }
1592 1775
1593 Py_RETURN_NONE; 1776 Py_RETURN_NONE;
1594 } 1777 }
1595 1778
1596 PyDoc_STRVAR(print_doc, 1779 PyDoc_STRVAR(print_doc,
1597 "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\ 1780 "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\
1598 \n\ 1781 \n\
1599 Prints the values to a stream, or to sys.stdout by default.\n\ 1782 Prints the values to a stream, or to sys.stdout by default.\n\
1600 Optional keyword arguments:\n\ 1783 Optional keyword arguments:\n\
1601 file: a file-like object (stream); defaults to the current sys.stdout.\n\ 1784 file: a file-like object (stream); defaults to the current sys.stdout.\n\
1602 sep: string inserted between values, default a space.\n\ 1785 sep: string inserted between values, default a space.\n\
1603 end: string appended after the last value, default a newline.\n\ 1786 end: string appended after the last value, default a newline.\n\
1604 flush: whether to forcibly flush the stream."); 1787 flush: whether to forcibly flush the stream.");
1605 1788
1606 1789
1607 static PyObject * 1790 /*[clinic input]
1608 builtin_input(PyObject *self, PyObject *args) 1791 input as builtin_input
1609 { 1792
1610 PyObject *promptarg = NULL; 1793 prompt: object(c_default="NULL") = None
1611 PyObject *fin = PySys_GetObject("stdin"); 1794 /
1612 PyObject *fout = PySys_GetObject("stdout"); 1795
1613 PyObject *ferr = PySys_GetObject("stderr"); 1796 Read a string from standard input. The trailing newline is stripped.
1797
1798 The prompt string, if given, is printed to standard output without a
1799 trailing newline before reading input.
1800
1801 If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
1802 On *nix systems, readline is used if available.
1803 [clinic start generated code]*/
1804
1805 static PyObject *
1806 builtin_input_impl(PyModuleDef *module, PyObject *prompt)
1807 /*[clinic end generated code: output=b77731f59e1515c4 input=5e8bb70c2908fe3c]*/
1808 {
1809 PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
1810 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1811 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1614 PyObject *tmp; 1812 PyObject *tmp;
1615 long fd; 1813 long fd;
1616 int tty; 1814 int tty;
1617
1618 /* Parse arguments */
1619 if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg))
1620 return NULL;
1621 1815
1622 /* Check that stdin/out/err are intact */ 1816 /* Check that stdin/out/err are intact */
1623 if (fin == NULL || fin == Py_None) { 1817 if (fin == NULL || fin == Py_None) {
1624 PyErr_SetString(PyExc_RuntimeError, 1818 PyErr_SetString(PyExc_RuntimeError,
1625 "input(): lost sys.stdin"); 1819 "input(): lost sys.stdin");
1626 return NULL; 1820 return NULL;
1627 } 1821 }
1628 if (fout == NULL || fout == Py_None) { 1822 if (fout == NULL || fout == Py_None) {
1629 PyErr_SetString(PyExc_RuntimeError, 1823 PyErr_SetString(PyExc_RuntimeError,
1630 "input(): lost sys.stdout"); 1824 "input(): lost sys.stdout");
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
1667 Py_DECREF(tmp); 1861 Py_DECREF(tmp);
1668 if (fd < 0 && PyErr_Occurred()) 1862 if (fd < 0 && PyErr_Occurred())
1669 return NULL; 1863 return NULL;
1670 tty = fd == fileno(stdout) && isatty(fd); 1864 tty = fd == fileno(stdout) && isatty(fd);
1671 } 1865 }
1672 } 1866 }
1673 1867
1674 /* If we're interactive, use (GNU) readline */ 1868 /* If we're interactive, use (GNU) readline */
1675 if (tty) { 1869 if (tty) {
1676 PyObject *po = NULL; 1870 PyObject *po = NULL;
1677 char *prompt; 1871 char *promptstr;
1678 char *s = NULL; 1872 char *s = NULL;
1679 PyObject *stdin_encoding = NULL, *stdin_errors = NULL; 1873 PyObject *stdin_encoding = NULL, *stdin_errors = NULL;
1680 PyObject *stdout_encoding = NULL, *stdout_errors = NULL; 1874 PyObject *stdout_encoding = NULL, *stdout_errors = NULL;
1681 char *stdin_encoding_str, *stdin_errors_str; 1875 char *stdin_encoding_str, *stdin_errors_str;
1682 PyObject *result; 1876 PyObject *result;
1683 size_t len; 1877 size_t len;
1684 _Py_IDENTIFIER(encoding);
1685 _Py_IDENTIFIER(errors);
1686 1878
1687 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding); 1879 stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding);
1688 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors); 1880 stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors);
1689 if (!stdin_encoding || !stdin_errors) 1881 if (!stdin_encoding || !stdin_errors ||
1882 !PyUnicode_Check(stdin_encoding) ||
1883 !PyUnicode_Check(stdin_errors))
1690 /* stdin is a text stream, so it must have an 1884 /* stdin is a text stream, so it must have an
1691 encoding. */ 1885 encoding. */
1692 goto _readline_errors; 1886 goto fallback;
1693 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding); 1887 stdin_encoding_str = _PyUnicode_AsString(stdin_encoding);
1694 stdin_errors_str = _PyUnicode_AsString(stdin_errors); 1888 stdin_errors_str = _PyUnicode_AsString(stdin_errors);
1695 if (!stdin_encoding_str || !stdin_errors_str) 1889 if (!stdin_encoding_str || !stdin_errors_str)
1696 goto _readline_errors; 1890 goto _readline_errors;
1697 tmp = _PyObject_CallMethodId(fout, &PyId_flush, ""); 1891 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
1698 if (tmp == NULL) 1892 if (tmp == NULL)
1699 PyErr_Clear(); 1893 PyErr_Clear();
1700 else 1894 else
1701 Py_DECREF(tmp); 1895 Py_DECREF(tmp);
1702 if (promptarg != NULL) { 1896 if (prompt != NULL) {
1703 /* We have a prompt, encode it as stdout would */ 1897 /* We have a prompt, encode it as stdout would */
1704 char *stdout_encoding_str, *stdout_errors_str; 1898 char *stdout_encoding_str, *stdout_errors_str;
1705 PyObject *stringpo; 1899 PyObject *stringpo;
1706 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding); 1900 stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding);
1707 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors); 1901 stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors);
1708 if (!stdout_encoding || !stdout_errors) 1902 if (!stdout_encoding || !stdout_errors ||
1709 goto _readline_errors; 1903 !PyUnicode_Check(stdout_encoding) ||
1904 !PyUnicode_Check(stdout_errors))
1905 goto fallback;
1710 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding); 1906 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1711 stdout_errors_str = _PyUnicode_AsString(stdout_errors); 1907 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1712 if (!stdout_encoding_str || !stdout_errors_str) { 1908 if (!stdout_encoding_str || !stdout_errors_str)
1713 /* invalid encoding or errors attributes on stdin, 1909 goto _readline_errors;
1714 check stderr for valid values */ 1910 stringpo = PyObject_Str(prompt);
1715 PyErr_Clear();
1716 stdout_encoding = _PyObject_GetAttrId(ferr, &PyId_encoding);
1717 stdout_errors = _PyObject_GetAttrId(ferr, &PyId_errors);
1718 if (!stdout_encoding || !stdout_errors)
1719 goto _readline_errors;
1720 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
1721 stdout_errors_str = _PyUnicode_AsString(stdout_errors);
1722 if (!stdout_encoding_str || !stdout_errors_str)
1723 goto _readline_errors;
1724 }
1725 stringpo = PyObject_Str(promptarg);
1726 if (stringpo == NULL) 1911 if (stringpo == NULL)
1727 goto _readline_errors; 1912 goto _readline_errors;
1728 po = PyUnicode_AsEncodedString(stringpo, 1913 po = PyUnicode_AsEncodedString(stringpo,
1729 stdout_encoding_str, stdout_errors_str); 1914 stdout_encoding_str, stdout_errors_str);
1730 Py_CLEAR(stdout_encoding); 1915 Py_CLEAR(stdout_encoding);
1731 Py_CLEAR(stdout_errors); 1916 Py_CLEAR(stdout_errors);
1732 Py_CLEAR(stringpo); 1917 Py_CLEAR(stringpo);
1733 if (po == NULL) 1918 if (po == NULL)
1734 goto _readline_errors; 1919 goto _readline_errors;
1735 prompt = PyBytes_AsString(po); 1920 promptstr = PyBytes_AsString(po);
1736 if (prompt == NULL) 1921 if (promptstr == NULL)
1737 goto _readline_errors; 1922 goto _readline_errors;
1738 } 1923 }
1739 else { 1924 else {
1740 po = NULL; 1925 po = NULL;
1741 prompt = ""; 1926 promptstr = "";
1742 } 1927 }
1743 s = PyOS_Readline(stdin, stdout, prompt); 1928 s = PyOS_Readline(stdin, stdout, promptstr);
1744 if (s == NULL) { 1929 if (s == NULL) {
1930 PyErr_CheckSignals();
1745 if (!PyErr_Occurred()) 1931 if (!PyErr_Occurred())
1746 PyErr_SetNone(PyExc_KeyboardInterrupt); 1932 PyErr_SetNone(PyExc_KeyboardInterrupt);
1747 goto _readline_errors; 1933 goto _readline_errors;
1748 } 1934 }
1749 1935
1750 len = strlen(s); 1936 len = strlen(s);
1751 if (len == 0) { 1937 if (len == 0) {
1752 PyErr_SetNone(PyExc_EOFError); 1938 PyErr_SetNone(PyExc_EOFError);
1753 result = NULL; 1939 result = NULL;
1754 } 1940 }
(...skipping 18 matching lines...) Expand all
1773 return result; 1959 return result;
1774 _readline_errors: 1960 _readline_errors:
1775 Py_XDECREF(stdin_encoding); 1961 Py_XDECREF(stdin_encoding);
1776 Py_XDECREF(stdout_encoding); 1962 Py_XDECREF(stdout_encoding);
1777 Py_XDECREF(stdin_errors); 1963 Py_XDECREF(stdin_errors);
1778 Py_XDECREF(stdout_errors); 1964 Py_XDECREF(stdout_errors);
1779 Py_XDECREF(po); 1965 Py_XDECREF(po);
1780 return NULL; 1966 return NULL;
1781 } 1967 }
1782 1968
1969 fallback:
1783 /* Fallback if we're not interactive */ 1970 /* Fallback if we're not interactive */
1784 if (promptarg != NULL) { 1971 PyErr_Clear();
1785 if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) 1972 if (prompt != NULL) {
1973 if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0)
1786 return NULL; 1974 return NULL;
1787 } 1975 }
1788 tmp = _PyObject_CallMethodId(fout, &PyId_flush, ""); 1976 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
1789 if (tmp == NULL) 1977 if (tmp == NULL)
1790 PyErr_Clear(); 1978 PyErr_Clear();
1791 else 1979 else
1792 Py_DECREF(tmp); 1980 Py_DECREF(tmp);
1793 return PyFile_GetLine(fin, -1); 1981 return PyFile_GetLine(fin, -1);
1794 } 1982 }
1795 1983
1796 PyDoc_STRVAR(input_doc, 1984
1797 "input([prompt]) -> string\n\ 1985 /*[clinic input]
1798 \n\ 1986 repr as builtin_repr
1799 Read a string from standard input. The trailing newline is stripped.\n\ 1987
1800 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\ 1988 obj: object
1801 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\ 1989 /
1802 is printed without a trailing newline before reading."); 1990
1803 1991 Return the canonical string representation of the object.
1804 1992
1805 static PyObject * 1993 For many object types, including most builtins, eval(repr(obj)) == obj.
1806 builtin_repr(PyObject *self, PyObject *v) 1994 [clinic start generated code]*/
1807 { 1995
1808 return PyObject_Repr(v); 1996 static PyObject *
1809 } 1997 builtin_repr(PyModuleDef *module, PyObject *obj)
1810 1998 /*[clinic end generated code: output=dc41784fa4341834 input=1c9e6d66d3e3be04]*/
1811 PyDoc_STRVAR(repr_doc, 1999 {
1812 "repr(object) -> string\n\ 2000 return PyObject_Repr(obj);
1813 \n\ 2001 }
1814 Return the canonical string representation of the object.\n\ 2002
1815 For most object types, eval(repr(object)) == object."); 2003
1816 2004 /* AC: cannot convert yet, as needs PEP 457 group support in inspect
1817 2005 * or a semantic change to accept None for "ndigits"
2006 */
1818 static PyObject * 2007 static PyObject *
1819 builtin_round(PyObject *self, PyObject *args, PyObject *kwds) 2008 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
1820 { 2009 {
1821 static PyObject *round_str = NULL;
1822 PyObject *ndigits = NULL; 2010 PyObject *ndigits = NULL;
1823 static char *kwlist[] = {"number", "ndigits", 0}; 2011 static char *kwlist[] = {"number", "ndigits", 0};
1824 PyObject *number, *round; 2012 PyObject *number, *round, *result;
1825 2013
1826 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", 2014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
1827 kwlist, &number, &ndigits)) 2015 kwlist, &number, &ndigits))
1828 return NULL; 2016 return NULL;
1829 2017
1830 if (Py_TYPE(number)->tp_dict == NULL) { 2018 if (Py_TYPE(number)->tp_dict == NULL) {
1831 if (PyType_Ready(Py_TYPE(number)) < 0) 2019 if (PyType_Ready(Py_TYPE(number)) < 0)
1832 return NULL; 2020 return NULL;
1833 } 2021 }
1834 2022
1835 if (round_str == NULL) { 2023 round = _PyObject_LookupSpecial(number, &PyId___round__);
1836 round_str = PyUnicode_InternFromString("__round__");
1837 if (round_str == NULL)
1838 return NULL;
1839 }
1840
1841 round = _PyType_Lookup(Py_TYPE(number), round_str);
1842 if (round == NULL) { 2024 if (round == NULL) {
1843 PyErr_Format(PyExc_TypeError, 2025 if (!PyErr_Occurred())
1844 "type %.100s doesn't define __round__ method", 2026 PyErr_Format(PyExc_TypeError,
1845 Py_TYPE(number)->tp_name); 2027 "type %.100s doesn't define __round__ method",
2028 Py_TYPE(number)->tp_name);
1846 return NULL; 2029 return NULL;
1847 } 2030 }
1848 2031
1849 if (ndigits == NULL) 2032 if (ndigits == NULL)
1850 return PyObject_CallFunction(round, "O", number); 2033 result = PyObject_CallFunctionObjArgs(round, NULL);
1851 else 2034 else
1852 return PyObject_CallFunction(round, "OO", number, ndigits); 2035 result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
2036 Py_DECREF(round);
2037 return result;
1853 } 2038 }
1854 2039
1855 PyDoc_STRVAR(round_doc, 2040 PyDoc_STRVAR(round_doc,
1856 "round(number[, ndigits]) -> number\n\ 2041 "round(number[, ndigits]) -> number\n\
1857 \n\ 2042 \n\
1858 Round a number to a given precision in decimal digits (default 0 digits).\n\ 2043 Round a number to a given precision in decimal digits (default 0 digits).\n\
1859 This returns an int when called with one argument, otherwise the\n\ 2044 This returns an int when called with one argument, otherwise the\n\
1860 same type as the number. ndigits may be negative."); 2045 same type as the number. ndigits may be negative.");
1861 2046
1862 2047
2048 /*AC: we need to keep the kwds dict intact to easily call into the
2049 * list.sort method, which isn't currently supported in AC. So we just use
2050 * the initially generated signature with a custom implementation.
2051 */
2052 /* [disabled clinic input]
2053 sorted as builtin_sorted
2054
2055 iterable as seq: object
2056 key as keyfunc: object = None
2057 reverse: object = False
2058
2059 Return a new list containing all items from the iterable in ascending order.
2060
2061 A custom key function can be supplied to customise the sort order, and the
2062 reverse flag can be set to request the result in descending order.
2063 [end disabled clinic input]*/
2064
2065 PyDoc_STRVAR(builtin_sorted__doc__,
2066 "sorted($module, iterable, key=None, reverse=False)\n"
2067 "--\n"
2068 "\n"
2069 "Return a new list containing all items from the iterable in ascending order.\n"
2070 "\n"
2071 "A custom key function can be supplied to customise the sort order, and the\n"
2072 "reverse flag can be set to request the result in descending order.");
2073
2074 #define BUILTIN_SORTED_METHODDEF \
2075 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS|METH_KEYWORDS, builtin_ sorted__doc__},
2076
1863 static PyObject * 2077 static PyObject *
1864 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) 2078 builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
1865 { 2079 {
1866 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; 2080 PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs;
1867 PyObject *callable; 2081 PyObject *callable;
1868 static char *kwlist[] = {"iterable", "key", "reverse", 0}; 2082 static char *kwlist[] = {"iterable", "key", "reverse", 0};
1869 int reverse; 2083 int reverse;
1870 _Py_IDENTIFIER(sort);
1871 2084
1872 /* args 1-3 should match listsort in Objects/listobject.c */ 2085 /* args 1-3 should match listsort in Objects/listobject.c */
1873 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", 2086 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted",
1874 kwlist, &seq, &keyfunc, &reverse)) 2087 kwlist, &seq, &keyfunc, &reverse))
1875 return NULL; 2088 return NULL;
1876 2089
1877 newlist = PySequence_List(seq); 2090 newlist = PySequence_List(seq);
1878 if (newlist == NULL) 2091 if (newlist == NULL)
1879 return NULL; 2092 return NULL;
1880 2093
(...skipping 14 matching lines...) Expand all
1895 Py_DECREF(newargs); 2108 Py_DECREF(newargs);
1896 Py_DECREF(callable); 2109 Py_DECREF(callable);
1897 if (v == NULL) { 2110 if (v == NULL) {
1898 Py_DECREF(newlist); 2111 Py_DECREF(newlist);
1899 return NULL; 2112 return NULL;
1900 } 2113 }
1901 Py_DECREF(v); 2114 Py_DECREF(v);
1902 return newlist; 2115 return newlist;
1903 } 2116 }
1904 2117
1905 PyDoc_STRVAR(sorted_doc, 2118
1906 "sorted(iterable, key=None, reverse=False) --> new sorted list"); 2119 /* AC: cannot convert yet, as needs PEP 457 group support in inspect */
1907
1908 static PyObject * 2120 static PyObject *
1909 builtin_vars(PyObject *self, PyObject *args) 2121 builtin_vars(PyObject *self, PyObject *args)
1910 { 2122 {
1911 PyObject *v = NULL; 2123 PyObject *v = NULL;
1912 PyObject *d; 2124 PyObject *d;
1913 2125
1914 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) 2126 if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
1915 return NULL; 2127 return NULL;
1916 if (v == NULL) { 2128 if (v == NULL) {
1917 d = PyEval_GetLocals(); 2129 d = PyEval_GetLocals();
1918 if (d == NULL) { 2130 if (d == NULL)
1919 if (!PyErr_Occurred()) 2131 return NULL;
1920 PyErr_SetString(PyExc_SystemError, 2132 Py_INCREF(d);
1921 "vars(): no locals!?");
1922 }
1923 else
1924 Py_INCREF(d);
1925 } 2133 }
1926 else { 2134 else {
1927 _Py_IDENTIFIER(__dict__);
1928 d = _PyObject_GetAttrId(v, &PyId___dict__); 2135 d = _PyObject_GetAttrId(v, &PyId___dict__);
1929 if (d == NULL) { 2136 if (d == NULL) {
1930 PyErr_SetString(PyExc_TypeError, 2137 PyErr_SetString(PyExc_TypeError,
1931 "vars() argument must have __dict__ attribute"); 2138 "vars() argument must have __dict__ attribute");
1932 return NULL; 2139 return NULL;
1933 } 2140 }
1934 } 2141 }
1935 return d; 2142 return d;
1936 } 2143 }
1937 2144
1938 PyDoc_STRVAR(vars_doc, 2145 PyDoc_STRVAR(vars_doc,
1939 "vars([object]) -> dictionary\n\ 2146 "vars([object]) -> dictionary\n\
1940 \n\ 2147 \n\
1941 Without arguments, equivalent to locals().\n\ 2148 Without arguments, equivalent to locals().\n\
1942 With an argument, equivalent to object.__dict__."); 2149 With an argument, equivalent to object.__dict__.");
1943 2150
1944 static PyObject* 2151
1945 builtin_sum(PyObject *self, PyObject *args) 2152 /*[clinic input]
1946 { 2153 sum as builtin_sum
1947 PyObject *seq; 2154
1948 PyObject *result = NULL; 2155 iterable: object
2156 start: object(c_default="NULL") = 0
2157 /
2158
2159 Return the sum of a 'start' value (default: 0) plus an iterable of numbers
2160
2161 When the iterable is empty, return the start value.
2162 This function is intended specifically for use with numeric values and may
2163 reject non-numeric types.
2164 [clinic start generated code]*/
2165
2166 static PyObject *
2167 builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
2168 /*[clinic end generated code: output=33655b248b21d581 input=3b5b7a9d7611c73a]*/
2169 {
2170 PyObject *result = start;
1949 PyObject *temp, *item, *iter; 2171 PyObject *temp, *item, *iter;
1950 2172
1951 if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) 2173 iter = PyObject_GetIter(iterable);
1952 return NULL;
1953
1954 iter = PyObject_GetIter(seq);
1955 if (iter == NULL) 2174 if (iter == NULL)
1956 return NULL; 2175 return NULL;
1957 2176
1958 if (result == NULL) { 2177 if (result == NULL) {
1959 result = PyLong_FromLong(0); 2178 result = PyLong_FromLong(0);
1960 if (result == NULL) { 2179 if (result == NULL) {
1961 Py_DECREF(iter); 2180 Py_DECREF(iter);
1962 return NULL; 2181 return NULL;
1963 } 2182 }
1964 } else { 2183 } else {
1965 /* reject string values for 'start' parameter */ 2184 /* reject string values for 'start' parameter */
1966 if (PyUnicode_Check(result)) { 2185 if (PyUnicode_Check(result)) {
1967 PyErr_SetString(PyExc_TypeError, 2186 PyErr_SetString(PyExc_TypeError,
1968 "sum() can't sum strings [use ''.join(seq) instead]"); 2187 "sum() can't sum strings [use ''.join(seq) instead]");
1969 Py_DECREF(iter); 2188 Py_DECREF(iter);
1970 return NULL; 2189 return NULL;
1971 } 2190 }
1972 if (PyBytes_Check(result)) { 2191 if (PyBytes_Check(result)) {
1973 PyErr_SetString(PyExc_TypeError, 2192 PyErr_SetString(PyExc_TypeError,
1974 "sum() can't sum bytes [use b''.join(seq) instead]"); 2193 "sum() can't sum bytes [use b''.join(seq) instead]");
1975 Py_DECREF(iter); 2194 Py_DECREF(iter);
1976 return NULL; 2195 return NULL;
1977 } 2196 }
1978 if (PyByteArray_Check(result)) { 2197 if (PyByteArray_Check(result)) {
1979 PyErr_SetString(PyExc_TypeError, 2198 PyErr_SetString(PyExc_TypeError,
1980 "sum() can't sum bytearray [use b''.join(seq) instead]"); 2199 "sum() can't sum bytearray [use b''.join(seq) instead]");
1981 Py_DECREF(iter); 2200 Py_DECREF(iter);
1982 return NULL; 2201 return NULL;
1983 } 2202 }
1984
1985 Py_INCREF(result); 2203 Py_INCREF(result);
1986 } 2204 }
1987 2205
1988 #ifndef SLOW_SUM 2206 #ifndef SLOW_SUM
1989 /* Fast addition by keeping temporary sums in C instead of new Python object s. 2207 /* Fast addition by keeping temporary sums in C instead of new Python object s.
1990 Assumes all inputs are the same type. If the assumption fails, default 2208 Assumes all inputs are the same type. If the assumption fails, default
1991 to the more general routine. 2209 to the more general routine.
1992 */ 2210 */
1993 if (PyLong_CheckExact(result)) { 2211 if (PyLong_CheckExact(result)) {
1994 int overflow; 2212 int overflow;
(...skipping 15 matching lines...) Expand all
2010 long b = PyLong_AsLongAndOverflow(item, &overflow); 2228 long b = PyLong_AsLongAndOverflow(item, &overflow);
2011 long x = i_result + b; 2229 long x = i_result + b;
2012 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { 2230 if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2013 i_result = x; 2231 i_result = x;
2014 Py_DECREF(item); 2232 Py_DECREF(item);
2015 continue; 2233 continue;
2016 } 2234 }
2017 } 2235 }
2018 /* Either overflowed or is not an int. Restore real objects and proc ess normally */ 2236 /* Either overflowed or is not an int. Restore real objects and proc ess normally */
2019 result = PyLong_FromLong(i_result); 2237 result = PyLong_FromLong(i_result);
2238 if (result == NULL) {
2239 Py_DECREF(item);
2240 Py_DECREF(iter);
2241 return NULL;
2242 }
2020 temp = PyNumber_Add(result, item); 2243 temp = PyNumber_Add(result, item);
2021 Py_DECREF(result); 2244 Py_DECREF(result);
2022 Py_DECREF(item); 2245 Py_DECREF(item);
2023 result = temp; 2246 result = temp;
2024 if (result == NULL) { 2247 if (result == NULL) {
2025 Py_DECREF(iter); 2248 Py_DECREF(iter);
2026 return NULL; 2249 return NULL;
2027 } 2250 }
2028 } 2251 }
2029 } 2252 }
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
2095 Py_DECREF(result); 2318 Py_DECREF(result);
2096 Py_DECREF(item); 2319 Py_DECREF(item);
2097 result = temp; 2320 result = temp;
2098 if (result == NULL) 2321 if (result == NULL)
2099 break; 2322 break;
2100 } 2323 }
2101 Py_DECREF(iter); 2324 Py_DECREF(iter);
2102 return result; 2325 return result;
2103 } 2326 }
2104 2327
2105 PyDoc_STRVAR(sum_doc, 2328
2106 "sum(iterable[, start]) -> value\n\ 2329 /*[clinic input]
2107 \n\ 2330 isinstance as builtin_isinstance
2108 Returns the sum of an iterable of numbers (NOT strings) plus the value\n\ 2331
2109 of parameter 'start' (which defaults to 0). When the iterable is\n\ 2332 obj: object
2110 empty, returns start."); 2333 class_or_tuple: object
2111 2334 /
2112 2335
2113 static PyObject * 2336 Return whether an object is an instance of a class or of a subclass thereof.
2114 builtin_isinstance(PyObject *self, PyObject *args) 2337
2115 { 2338 A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
2116 PyObject *inst; 2339 check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
2117 PyObject *cls; 2340 or ...`` etc.
2341 [clinic start generated code]*/
2342
2343 static PyObject *
2344 builtin_isinstance_impl(PyModuleDef *module, PyObject *obj,
2345 PyObject *class_or_tuple)
2346 /*[clinic end generated code: output=f960b7c12dbbeda0 input=ffa743db1daf7549]*/
2347 {
2118 int retval; 2348 int retval;
2119 2349
2120 if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) 2350 retval = PyObject_IsInstance(obj, class_or_tuple);
2121 return NULL;
2122
2123 retval = PyObject_IsInstance(inst, cls);
2124 if (retval < 0) 2351 if (retval < 0)
2125 return NULL; 2352 return NULL;
2126 return PyBool_FromLong(retval); 2353 return PyBool_FromLong(retval);
2127 } 2354 }
2128 2355
2129 PyDoc_STRVAR(isinstance_doc, 2356
2130 "isinstance(object, class-or-type-or-tuple) -> bool\n\ 2357 /*[clinic input]
2131 \n\ 2358 issubclass as builtin_issubclass
2132 Return whether an object is an instance of a class or of a subclass thereof.\n\ 2359
2133 With a type as second argument, return whether that is the object's type.\n\ 2360 cls: object
2134 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\ 2361 class_or_tuple: object
2135 isinstance(x, A) or isinstance(x, B) or ... (etc.)."); 2362 /
2136 2363
2137 2364 Return whether 'cls' is a derived from another class or is the same class.
2138 static PyObject * 2365
2139 builtin_issubclass(PyObject *self, PyObject *args) 2366 A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
2140 { 2367 check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
2141 PyObject *derived; 2368 or ...`` etc.
2142 PyObject *cls; 2369 [clinic start generated code]*/
2370
2371 static PyObject *
2372 builtin_issubclass_impl(PyModuleDef *module, PyObject *cls,
2373 PyObject *class_or_tuple)
2374 /*[clinic end generated code: output=8b012a151940bbf2 input=af5f35e9ceaddaf6]*/
2375 {
2143 int retval; 2376 int retval;
2144 2377
2145 if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) 2378 retval = PyObject_IsSubclass(cls, class_or_tuple);
2146 return NULL;
2147
2148 retval = PyObject_IsSubclass(derived, cls);
2149 if (retval < 0) 2379 if (retval < 0)
2150 return NULL; 2380 return NULL;
2151 return PyBool_FromLong(retval); 2381 return PyBool_FromLong(retval);
2152 } 2382 }
2153
2154 PyDoc_STRVAR(issubclass_doc,
2155 "issubclass(C, B) -> bool\n\
2156 \n\
2157 Return whether class C is a subclass (i.e., a derived class) of class B.\n\
2158 When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
2159 is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
2160 2383
2161 2384
2162 typedef struct { 2385 typedef struct {
2163 PyObject_HEAD 2386 PyObject_HEAD
2164 Py_ssize_t tuplesize; 2387 Py_ssize_t tuplesize;
2165 PyObject *ittuple; /* tuple of iterators */ 2388 PyObject *ittuple; /* tuple of iterators */
2166 PyObject *result; 2389 PyObject *result;
2167 } zipobject; 2390 } zipobject;
2168 2391
2169 static PyObject * 2392 static PyObject *
(...skipping 175 matching lines...) Expand 10 before | Expand all | Expand 10 after
2345 PyType_GenericAlloc, /* tp_alloc */ 2568 PyType_GenericAlloc, /* tp_alloc */
2346 zip_new, /* tp_new */ 2569 zip_new, /* tp_new */
2347 PyObject_GC_Del, /* tp_free */ 2570 PyObject_GC_Del, /* tp_free */
2348 }; 2571 };
2349 2572
2350 2573
2351 static PyMethodDef builtin_methods[] = { 2574 static PyMethodDef builtin_methods[] = {
2352 {"__build_class__", (PyCFunction)builtin___build_class__, 2575 {"__build_class__", (PyCFunction)builtin___build_class__,
2353 METH_VARARGS | METH_KEYWORDS, build_class_doc}, 2576 METH_VARARGS | METH_KEYWORDS, build_class_doc},
2354 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEY WORDS, import_doc}, 2577 {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEY WORDS, import_doc},
2355 {"abs", builtin_abs, METH_O, abs_doc}, 2578 BUILTIN_ABS_METHODDEF
2356 {"all", builtin_all, METH_O, all_doc}, 2579 BUILTIN_ALL_METHODDEF
2357 {"any", builtin_any, METH_O, any_doc}, 2580 BUILTIN_ANY_METHODDEF
2358 {"ascii", builtin_ascii, METH_O, ascii_doc}, 2581 BUILTIN_ASCII_METHODDEF
2359 {"bin", builtin_bin, METH_O, bin_doc}, 2582 BUILTIN_BIN_METHODDEF
2360 {"callable", builtin_callable, METH_O, callable_doc}, 2583 BUILTIN_CALLABLE_METHODDEF
2361 {"chr", builtin_chr, METH_VARARGS, chr_doc}, 2584 BUILTIN_CHR_METHODDEF
2362 {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEY WORDS, compile_doc}, 2585 BUILTIN_COMPILE_METHODDEF
2363 {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, 2586 BUILTIN_DELATTR_METHODDEF
2364 {"dir", builtin_dir, METH_VARARGS, dir_doc}, 2587 {"dir", builtin_dir, METH_VARARGS, dir_doc},
2365 {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, 2588 BUILTIN_DIVMOD_METHODDEF
2366 {"eval", builtin_eval, METH_VARARGS, eval_doc}, 2589 BUILTIN_EVAL_METHODDEF
2367 {"exec", builtin_exec, METH_VARARGS, exec_doc}, 2590 BUILTIN_EXEC_METHODDEF
2368 {"format", builtin_format, METH_VARARGS, format_doc}, 2591 BUILTIN_FORMAT_METHODDEF
2369 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, 2592 {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
2370 {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_do c}, 2593 BUILTIN_GLOBALS_METHODDEF
2371 {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, 2594 BUILTIN_HASATTR_METHODDEF
2372 {"hash", builtin_hash, METH_O, hash_doc}, 2595 BUILTIN_HASH_METHODDEF
2373 {"hex", builtin_hex, METH_O, hex_doc}, 2596 BUILTIN_HEX_METHODDEF
2374 {"id", builtin_id, METH_O, id_doc}, 2597 BUILTIN_ID_METHODDEF
2375 {"input", builtin_input, METH_VARARGS, input_doc}, 2598 BUILTIN_INPUT_METHODDEF
2376 {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, 2599 BUILTIN_ISINSTANCE_METHODDEF
2377 {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, 2600 BUILTIN_ISSUBCLASS_METHODDEF
2378 {"iter", builtin_iter, METH_VARARGS, iter_doc}, 2601 {"iter", builtin_iter, METH_VARARGS, iter_doc},
2379 {"len", builtin_len, METH_O, len_doc}, 2602 BUILTIN_LEN_METHODDEF
2380 {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc }, 2603 BUILTIN_LOCALS_METHODDEF
2381 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEY WORDS, max_doc}, 2604 {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEY WORDS, max_doc},
2382 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEY WORDS, min_doc}, 2605 {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEY WORDS, min_doc},
2383 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc} , 2606 {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc} ,
2384 {"oct", builtin_oct, METH_O, oct_doc}, 2607 BUILTIN_OCT_METHODDEF
2385 {"ord", builtin_ord, METH_O, ord_doc}, 2608 BUILTIN_ORD_METHODDEF
2386 {"pow", builtin_pow, METH_VARARGS, pow_doc}, 2609 BUILTIN_POW_METHODDEF
2387 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEY WORDS, print_doc}, 2610 {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEY WORDS, print_doc},
2388 {"repr", builtin_repr, METH_O, repr_doc}, 2611 BUILTIN_REPR_METHODDEF
2389 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEY WORDS, round_doc}, 2612 {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEY WORDS, round_doc},
2390 {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, 2613 BUILTIN_SETATTR_METHODDEF
2391 {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEY WORDS, sorted_doc}, 2614 BUILTIN_SORTED_METHODDEF
2392 {"sum", builtin_sum, METH_VARARGS, sum_doc}, 2615 BUILTIN_SUM_METHODDEF
2393 {"vars", builtin_vars, METH_VARARGS, vars_doc}, 2616 {"vars", builtin_vars, METH_VARARGS, vars_doc},
2394 {NULL, NULL}, 2617 {NULL, NULL},
2395 }; 2618 };
2396 2619
2397 PyDoc_STRVAR(builtin_doc, 2620 PyDoc_STRVAR(builtin_doc,
2398 "Built-in functions, exceptions, and other objects.\n\ 2621 "Built-in functions, exceptions, and other objects.\n\
2399 \n\ 2622 \n\
2400 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."); 2623 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
2401 2624
2402 static struct PyModuleDef builtinsmodule = { 2625 static struct PyModuleDef builtinsmodule = {
2403 PyModuleDef_HEAD_INIT, 2626 PyModuleDef_HEAD_INIT,
2404 "builtins", 2627 "builtins",
2405 builtin_doc, 2628 builtin_doc,
2406 -1, /* multiple "initialization" just copies the module dict. */ 2629 -1, /* multiple "initialization" just copies the module dict. */
2407 builtin_methods, 2630 builtin_methods,
2408 NULL, 2631 NULL,
2409 NULL, 2632 NULL,
2410 NULL, 2633 NULL,
2411 NULL 2634 NULL
2412 }; 2635 };
2413 2636
2414 2637
2415 PyObject * 2638 PyObject *
2416 _PyBuiltin_Init(void) 2639 _PyBuiltin_Init(void)
2417 { 2640 {
2418 PyObject *mod, *dict, *debug; 2641 PyObject *mod, *dict, *debug;
2642
2643 if (PyType_Ready(&PyFilter_Type) < 0 ||
2644 PyType_Ready(&PyMap_Type) < 0 ||
2645 PyType_Ready(&PyZip_Type) < 0)
2646 return NULL;
2647
2419 mod = PyModule_Create(&builtinsmodule); 2648 mod = PyModule_Create(&builtinsmodule);
2420 if (mod == NULL) 2649 if (mod == NULL)
2421 return NULL; 2650 return NULL;
2422 dict = PyModule_GetDict(mod); 2651 dict = PyModule_GetDict(mod);
2423 2652
2424 #ifdef Py_TRACE_REFS 2653 #ifdef Py_TRACE_REFS
2425 /* "builtins" exposes a number of statically allocated objects 2654 /* "builtins" exposes a number of statically allocated objects
2426 * that, before this code was added in 2.3, never showed up in 2655 * that, before this code was added in 2.3, never showed up in
2427 * the list of "all objects" maintained by Py_TRACE_REFS. As a 2656 * the list of "all objects" maintained by Py_TRACE_REFS. As a
2428 * result, programs leaking references to None and False (etc) 2657 * result, programs leaking references to None and False (etc)
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
2473 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { 2702 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2474 Py_XDECREF(debug); 2703 Py_XDECREF(debug);
2475 return NULL; 2704 return NULL;
2476 } 2705 }
2477 Py_XDECREF(debug); 2706 Py_XDECREF(debug);
2478 2707
2479 return mod; 2708 return mod;
2480 #undef ADD_TO_ALL 2709 #undef ADD_TO_ALL
2481 #undef SETBUILTIN 2710 #undef SETBUILTIN
2482 } 2711 }
LEFTRIGHT
« no previous file | no next file » | Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Toggle Comments ('s')

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+