bltinmodule.c revision b18618dab7b6b85bb05b084693706e59211fa180
1/*********************************************************** 2Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, 3The Netherlands. 4 5 All Rights Reserved 6 7Permission to use, copy, modify, and distribute this software and its 8documentation for any purpose and without fee is hereby granted, 9provided that the above copyright notice appear in all copies and that 10both that copyright notice and this permission notice appear in 11supporting documentation, and that the names of Stichting Mathematisch 12Centrum or CWI or Corporation for National Research Initiatives or 13CNRI not be used in advertising or publicity pertaining to 14distribution of the software without specific, written prior 15permission. 16 17While CWI is the initial source for this software, a modified version 18is made available by the Corporation for National Research Initiatives 19(CNRI) at the Internet address ftp://ftp.python.org. 20 21STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH 22REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF 23MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH 24CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL 25DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR 26PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER 27TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 28PERFORMANCE OF THIS SOFTWARE. 29 30******************************************************************/ 31 32/* Built-in functions */ 33 34#include "Python.h" 35 36#include "node.h" 37#include "compile.h" 38#include "eval.h" 39 40#include "mymath.h" 41 42#include <ctype.h> 43 44#ifdef HAVE_UNISTD_H 45#include <unistd.h> 46#endif 47 48/* Forward */ 49static PyObject *filterstring Py_PROTO((PyObject *, PyObject *)); 50static PyObject *filtertuple Py_PROTO((PyObject *, PyObject *)); 51 52static PyObject * 53builtin___import__(self, args) 54 PyObject *self; 55 PyObject *args; 56{ 57 char *name; 58 PyObject *globals = NULL; 59 PyObject *locals = NULL; 60 PyObject *fromlist = NULL; 61 62 if (!PyArg_ParseTuple(args, "s|OOO:__import__", 63 &name, &globals, &locals, &fromlist)) 64 return NULL; 65 return PyImport_ImportModuleEx(name, globals, locals, fromlist); 66} 67 68static char import_doc[] = 69"__import__(name, globals, locals, fromlist) -> module\n\ 70\n\ 71Import a module. The globals are only used to determine the context;\n\ 72they are not modified. The locals are currently unused. The fromlist\n\ 73should be a list of names to emulate ``from name import ...'', or an\n\ 74empty list to emulate ``import name''.\n\ 75When importing a module from a package, note that __import__('A.B', ...)\n\ 76returns package A when fromlist is empty, but its submodule B when\n\ 77fromlist is not empty."; 78 79 80static PyObject * 81builtin_abs(self, args) 82 PyObject *self; 83 PyObject *args; 84{ 85 PyObject *v; 86 87 if (!PyArg_ParseTuple(args, "O:abs", &v)) 88 return NULL; 89 return PyNumber_Absolute(v); 90} 91 92static char abs_doc[] = 93"abs(number) -> number\n\ 94\n\ 95Return the absolute value of the argument."; 96 97 98static PyObject * 99builtin_apply(self, args) 100 PyObject *self; 101 PyObject *args; 102{ 103 PyObject *func, *alist = NULL, *kwdict = NULL; 104 PyObject *t = NULL, *retval = NULL; 105 106 if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict)) 107 return NULL; 108 if (alist != NULL) { 109 if (!PyTuple_Check(alist)) { 110 if (!PySequence_Check(alist)) { 111 PyErr_SetString(PyExc_TypeError, 112 "apply() 2nd argument must be a sequence"); 113 return NULL; 114 } 115 t = PySequence_Tuple(alist); 116 if (t == NULL) 117 return NULL; 118 alist = t; 119 } 120 } 121 if (kwdict != NULL && !PyDict_Check(kwdict)) { 122 PyErr_SetString(PyExc_TypeError, 123 "apply() 3rd argument must be dictionary"); 124 goto finally; 125 } 126 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict); 127 finally: 128 Py_XDECREF(t); 129 return retval; 130} 131 132static char apply_doc[] = 133"apply(object, args[, kwargs]) -> value\n\ 134\n\ 135Call a callable object with positional arguments taken from the tuple args,\n\ 136and keyword arguments taken from the optional dictionary kwargs.\n\ 137Note that classes are callable, as are instances with a __call__() method."; 138 139 140static PyObject * 141builtin_buffer(self, args) 142 PyObject *self; 143 PyObject *args; 144{ 145 PyObject *ob; 146 int offset = 0; 147 int size = Py_END_OF_BUFFER; 148 149 if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) ) 150 return NULL; 151 return PyBuffer_FromObject(ob, offset, size); 152} 153 154static char buffer_doc[] = 155"buffer(object [, offset[, size]]) -> object\n\ 156\n\ 157Creates a new buffer object which references the given object.\n\ 158The buffer will reference a slice of the target object from the\n\ 159start of the object (or at the specified offset). The slice will\n\ 160extend to the end of the target object (or with the specified size)."; 161 162 163static PyObject * 164builtin_unicode(self, args) 165 PyObject *self; 166 PyObject *args; 167{ 168 PyObject *v; 169 const void *buffer; 170 int len; 171 char *encoding = NULL; 172 char *errors = NULL; 173 174 if ( !PyArg_ParseTuple(args, "O|ss:unicode", &v, &encoding, &errors) ) 175 return NULL; 176 /* Special case: Unicode will stay Unicode */ 177 if (PyUnicode_Check(v)) { 178 if (encoding) { 179 PyErr_SetString(PyExc_TypeError, 180 "unicode() does not support decoding of Unicode objects"); 181 return NULL; 182 } 183 Py_INCREF(v); 184 return v; 185 } 186 /* Read raw data and decode it */ 187 if (PyObject_AsReadBuffer(v, &buffer, &len)) 188 return NULL; 189 return PyUnicode_Decode((const char *)buffer, len, encoding, errors); 190} 191 192static char unicode_doc[] = 193"unicode(string [, encoding[, errors]]) -> object\n\ 194\n\ 195Creates a new Unicode object from the given encoded string.\n\ 196encoding defaults to 'utf-8' and errors, defining the error handling,\n\ 197to 'strict'."; 198 199 200static PyObject * 201builtin_callable(self, args) 202 PyObject *self; 203 PyObject *args; 204{ 205 PyObject *v; 206 207 if (!PyArg_ParseTuple(args, "O:callable", &v)) 208 return NULL; 209 return PyInt_FromLong((long)PyCallable_Check(v)); 210} 211 212static char callable_doc[] = 213"callable(object) -> Boolean\n\ 214\n\ 215Return whether the object is callable (i.e., some kind of function).\n\ 216Note that classes are callable, as are instances with a __call__() method."; 217 218 219static PyObject * 220builtin_filter(self, args) 221 PyObject *self; 222 PyObject *args; 223{ 224 PyObject *func, *seq, *result; 225 PySequenceMethods *sqf; 226 int len; 227 register int i, j; 228 229 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq)) 230 return NULL; 231 232 if (PyString_Check(seq)) { 233 PyObject *r = filterstring(func, seq); 234 return r; 235 } 236 237 if (PyTuple_Check(seq)) { 238 PyObject *r = filtertuple(func, seq); 239 return r; 240 } 241 242 sqf = seq->ob_type->tp_as_sequence; 243 if (sqf == NULL || sqf->sq_length == NULL || sqf->sq_item == NULL) { 244 PyErr_SetString(PyExc_TypeError, 245 "argument 2 to filter() must be a sequence type"); 246 goto Fail_2; 247 } 248 249 if ((len = (*sqf->sq_length)(seq)) < 0) 250 goto Fail_2; 251 252 if (PyList_Check(seq) && seq->ob_refcnt == 1) { 253 Py_INCREF(seq); 254 result = seq; 255 } 256 else { 257 if ((result = PyList_New(len)) == NULL) 258 goto Fail_2; 259 } 260 261 for (i = j = 0; ; ++i) { 262 PyObject *item, *good; 263 int ok; 264 265 if ((item = (*sqf->sq_item)(seq, i)) == NULL) { 266 if (PyErr_ExceptionMatches(PyExc_IndexError)) { 267 PyErr_Clear(); 268 break; 269 } 270 goto Fail_1; 271 } 272 273 if (func == Py_None) { 274 good = item; 275 Py_INCREF(good); 276 } 277 else { 278 PyObject *arg = Py_BuildValue("(O)", item); 279 if (arg == NULL) 280 goto Fail_1; 281 good = PyEval_CallObject(func, arg); 282 Py_DECREF(arg); 283 if (good == NULL) { 284 Py_DECREF(item); 285 goto Fail_1; 286 } 287 } 288 ok = PyObject_IsTrue(good); 289 Py_DECREF(good); 290 if (ok) { 291 if (j < len) { 292 if (PyList_SetItem(result, j++, item) < 0) 293 goto Fail_1; 294 } 295 else { 296 int status = PyList_Append(result, item); 297 j++; 298 Py_DECREF(item); 299 if (status < 0) 300 goto Fail_1; 301 } 302 } else { 303 Py_DECREF(item); 304 } 305 } 306 307 308 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0) 309 goto Fail_1; 310 311 return result; 312 313Fail_1: 314 Py_DECREF(result); 315Fail_2: 316 return NULL; 317} 318 319static char filter_doc[] = 320"filter(function, sequence) -> list\n\ 321\n\ 322Return a list containing those items of sequence for which function(item)\n\ 323is true. If function is None, return a list of items that are true."; 324 325 326static PyObject * 327builtin_chr(self, args) 328 PyObject *self; 329 PyObject *args; 330{ 331 long x; 332 char s[1]; 333 334 if (!PyArg_ParseTuple(args, "l:chr", &x)) 335 return NULL; 336 if (x < 0 || x >= 256) { 337 PyErr_SetString(PyExc_ValueError, 338 "chr() arg not in range(256)"); 339 return NULL; 340 } 341 s[0] = (char)x; 342 return PyString_FromStringAndSize(s, 1); 343} 344 345static char chr_doc[] = 346"chr(i) -> character\n\ 347\n\ 348Return a string of one character with ordinal i; 0 <= i < 256."; 349 350 351static PyObject * 352builtin_unichr(self, args) 353 PyObject *self; 354 PyObject *args; 355{ 356 long x; 357 Py_UNICODE s[1]; 358 359 if (!PyArg_ParseTuple(args, "l:unichr", &x)) 360 return NULL; 361 if (x < 0 || x >= 65536) { 362 PyErr_SetString(PyExc_ValueError, 363 "unichr() arg not in range(65536)"); 364 return NULL; 365 } 366 s[0] = (Py_UNICODE)x; 367 return PyUnicode_FromUnicode(s, 1); 368} 369 370static char unichr_doc[] = 371"unichr(i) -> Unicode character\n\ 372\n\ 373Return a Unicode string of one character with ordinal i; 0 <= i < 65536."; 374 375 376static PyObject * 377builtin_cmp(self, args) 378 PyObject *self; 379 PyObject *args; 380{ 381 PyObject *a, *b; 382 int c; 383 384 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b)) 385 return NULL; 386 if (PyObject_Cmp(a, b, &c) < 0) 387 return NULL; 388 return PyInt_FromLong((long)c); 389} 390 391static char cmp_doc[] = 392"cmp(x, y) -> integer\n\ 393\n\ 394Return negative if x<y, zero if x==y, positive if x>y."; 395 396 397static PyObject * 398builtin_coerce(self, args) 399 PyObject *self; 400 PyObject *args; 401{ 402 PyObject *v, *w; 403 PyObject *res; 404 405 if (!PyArg_ParseTuple(args, "OO:coerce", &v, &w)) 406 return NULL; 407 if (PyNumber_Coerce(&v, &w) < 0) 408 return NULL; 409 res = Py_BuildValue("(OO)", v, w); 410 Py_DECREF(v); 411 Py_DECREF(w); 412 return res; 413} 414 415static char coerce_doc[] = 416"coerce(x, y) -> None or (x1, y1)\n\ 417\n\ 418When x and y can be coerced to values of the same type, return a tuple\n\ 419containing the coerced values. When they can't be coerced, return None."; 420 421 422static PyObject * 423builtin_compile(self, args) 424 PyObject *self; 425 PyObject *args; 426{ 427 char *str; 428 char *filename; 429 char *startstr; 430 int start; 431 432 if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr)) 433 return NULL; 434 if (strcmp(startstr, "exec") == 0) 435 start = Py_file_input; 436 else if (strcmp(startstr, "eval") == 0) 437 start = Py_eval_input; 438 else if (strcmp(startstr, "single") == 0) 439 start = Py_single_input; 440 else { 441 PyErr_SetString(PyExc_ValueError, 442 "compile() mode must be 'exec' or 'eval' or 'single'"); 443 return NULL; 444 } 445 return Py_CompileString(str, filename, start); 446} 447 448static char compile_doc[] = 449"compile(source, filename, mode) -> code object\n\ 450\n\ 451Compile the source string (a Python module, statement or expression)\n\ 452into a code object that can be executed by the exec statement or eval().\n\ 453The filename will be used for run-time error messages.\n\ 454The mode must be 'exec' to compile a module, 'single' to compile a\n\ 455single (interactive) statement, or 'eval' to compile an expression."; 456 457 458#ifndef WITHOUT_COMPLEX 459 460static PyObject * 461complex_from_string(v) 462 PyObject *v; 463{ 464 extern double strtod Py_PROTO((const char *, char **)); 465 const char *s, *start; 466 char *end; 467 double x=0.0, y=0.0, z; 468 int got_re=0, got_im=0, done=0; 469 int digit_or_dot; 470 int sw_error=0; 471 int sign; 472 char buffer[256]; /* For errors */ 473 int len; 474 475 if (PyString_Check(v)) { 476 s = PyString_AS_STRING(v); 477 len = PyString_GET_SIZE(v); 478 } 479 else if (PyUnicode_Check(v)) { 480 char s_buffer[256]; 481 482 if (PyUnicode_GET_SIZE(v) >= sizeof(s_buffer)) { 483 PyErr_SetString(PyExc_ValueError, 484 "complex() literal too large to convert"); 485 return NULL; 486 } 487 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), 488 PyUnicode_GET_SIZE(v), 489 s_buffer, 490 NULL)) 491 return NULL; 492 s = s_buffer; 493 len = strlen(s); 494 } 495 else if (PyObject_AsCharBuffer(v, &s, &len)) { 496 PyErr_SetString(PyExc_TypeError, 497 "complex() needs a string first argument"); 498 return NULL; 499 } 500 501 /* position on first nonblank */ 502 start = s; 503 while (*s && isspace(Py_CHARMASK(*s))) 504 s++; 505 if (s[0] == '\0') { 506 PyErr_SetString(PyExc_ValueError, 507 "empty string for complex()"); 508 return NULL; 509 } 510 511 z = -1.0; 512 sign = 1; 513 do { 514 515 switch (*s) { 516 517 case '\0': 518 if (s-start != len) { 519 PyErr_SetString( 520 PyExc_ValueError, 521 "null byte in argument for complex()"); 522 return NULL; 523 } 524 if(!done) sw_error=1; 525 break; 526 527 case '-': 528 sign = -1; 529 /* Fallthrough */ 530 case '+': 531 if (done) sw_error=1; 532 s++; 533 if ( *s=='\0'||*s=='+'||*s=='-' || 534 isspace(Py_CHARMASK(*s)) ) sw_error=1; 535 break; 536 537 case 'J': 538 case 'j': 539 if (got_im || done) { 540 sw_error = 1; 541 break; 542 } 543 if (z<0.0) { 544 y=sign; 545 } 546 else{ 547 y=sign*z; 548 } 549 got_im=1; 550 s++; 551 if (*s!='+' && *s!='-' ) 552 done=1; 553 break; 554 555 default: 556 if (isspace(Py_CHARMASK(*s))) { 557 while (*s && isspace(Py_CHARMASK(*s))) 558 s++; 559 if (s[0] != '\0') 560 sw_error=1; 561 else 562 done = 1; 563 break; 564 } 565 digit_or_dot = 566 (*s=='.' || isdigit(Py_CHARMASK(*s))); 567 if (done||!digit_or_dot) { 568 sw_error=1; 569 break; 570 } 571 errno = 0; 572 PyFPE_START_PROTECT("strtod", return 0) 573 z = strtod(s, &end) ; 574 PyFPE_END_PROTECT(z) 575 if (errno != 0) { 576 sprintf(buffer, 577 "float() out of range: %.150s", s); 578 PyErr_SetString( 579 PyExc_ValueError, 580 buffer); 581 return NULL; 582 } 583 s=end; 584 if (*s=='J' || *s=='j') { 585 586 break; 587 } 588 if (got_re) { 589 sw_error=1; 590 break; 591 } 592 593 /* accept a real part */ 594 x=sign*z; 595 got_re=1; 596 if (got_im) done=1; 597 z = -1.0; 598 sign = 1; 599 break; 600 601 } /* end of switch */ 602 603 } while (*s!='\0' && !sw_error); 604 605 if (sw_error) { 606 PyErr_SetString(PyExc_ValueError, 607 "malformed string for complex()"); 608 return NULL; 609 } 610 611 return PyComplex_FromDoubles(x,y); 612} 613 614static PyObject * 615builtin_complex(self, args) 616 PyObject *self; 617 PyObject *args; 618{ 619 PyObject *r, *i, *tmp; 620 PyNumberMethods *nbr, *nbi = NULL; 621 Py_complex cr, ci; 622 int own_r = 0; 623 624 i = NULL; 625 if (!PyArg_ParseTuple(args, "O|O:complex", &r, &i)) 626 return NULL; 627 if (PyString_Check(r) || PyUnicode_Check(r)) 628 return complex_from_string(r); 629 if ((nbr = r->ob_type->tp_as_number) == NULL || 630 nbr->nb_float == NULL || 631 (i != NULL && 632 ((nbi = i->ob_type->tp_as_number) == NULL || 633 nbi->nb_float == NULL))) { 634 PyErr_SetString(PyExc_TypeError, 635 "complex() argument can't be converted to complex"); 636 return NULL; 637 } 638 /* XXX Hack to support classes with __complex__ method */ 639 if (PyInstance_Check(r)) { 640 static PyObject *complexstr; 641 PyObject *f; 642 if (complexstr == NULL) { 643 complexstr = PyString_InternFromString("__complex__"); 644 if (complexstr == NULL) 645 return NULL; 646 } 647 f = PyObject_GetAttr(r, complexstr); 648 if (f == NULL) 649 PyErr_Clear(); 650 else { 651 PyObject *args = Py_BuildValue("()"); 652 if (args == NULL) 653 return NULL; 654 r = PyEval_CallObject(f, args); 655 Py_DECREF(args); 656 Py_DECREF(f); 657 if (r == NULL) 658 return NULL; 659 own_r = 1; 660 } 661 } 662 if (PyComplex_Check(r)) { 663 cr = ((PyComplexObject*)r)->cval; 664 if (own_r) { 665 Py_DECREF(r); 666 } 667 } 668 else { 669 tmp = (*nbr->nb_float)(r); 670 if (own_r) { 671 Py_DECREF(r); 672 } 673 if (tmp == NULL) 674 return NULL; 675 cr.real = PyFloat_AsDouble(tmp); 676 Py_DECREF(tmp); 677 cr.imag = 0.0; 678 } 679 if (i == NULL) { 680 ci.real = 0.0; 681 ci.imag = 0.0; 682 } 683 else if (PyComplex_Check(i)) 684 ci = ((PyComplexObject*)i)->cval; 685 else { 686 tmp = (*nbi->nb_float)(i); 687 if (tmp == NULL) 688 return NULL; 689 ci.real = PyFloat_AsDouble(tmp); 690 Py_DECREF(tmp); 691 ci.imag = 0.; 692 } 693 cr.real -= ci.imag; 694 cr.imag += ci.real; 695 return PyComplex_FromCComplex(cr); 696} 697 698static char complex_doc[] = 699"complex(real[, imag]) -> complex number\n\ 700\n\ 701Create a complex number from a real part and an optional imaginary part.\n\ 702This is equivalent to (real + imag*1j) where imag defaults to 0."; 703 704 705#endif 706 707static PyObject * 708builtin_dir(self, args) 709 PyObject *self; 710 PyObject *args; 711{ 712 static char *attrlist[] = {"__members__", "__methods__", NULL}; 713 PyObject *v = NULL, *l = NULL, *m = NULL; 714 PyObject *d, *x; 715 int i; 716 char **s; 717 718 if (!PyArg_ParseTuple(args, "|O:dir", &v)) 719 return NULL; 720 if (v == NULL) { 721 x = PyEval_GetLocals(); 722 if (x == NULL) 723 goto error; 724 l = PyMapping_Keys(x); 725 if (l == NULL) 726 goto error; 727 } 728 else { 729 d = PyObject_GetAttrString(v, "__dict__"); 730 if (d == NULL) 731 PyErr_Clear(); 732 else { 733 l = PyMapping_Keys(d); 734 if (l == NULL) 735 PyErr_Clear(); 736 Py_DECREF(d); 737 } 738 if (l == NULL) { 739 l = PyList_New(0); 740 if (l == NULL) 741 goto error; 742 } 743 for (s = attrlist; *s != NULL; s++) { 744 m = PyObject_GetAttrString(v, *s); 745 if (m == NULL) { 746 PyErr_Clear(); 747 continue; 748 } 749 for (i = 0; ; i++) { 750 x = PySequence_GetItem(m, i); 751 if (x == NULL) { 752 PyErr_Clear(); 753 break; 754 } 755 if (PyList_Append(l, x) != 0) { 756 Py_DECREF(x); 757 Py_DECREF(m); 758 goto error; 759 } 760 Py_DECREF(x); 761 } 762 Py_DECREF(m); 763 } 764 } 765 if (PyList_Sort(l) != 0) 766 goto error; 767 return l; 768 error: 769 Py_XDECREF(l); 770 return NULL; 771} 772 773static char dir_doc[] = 774"dir([object]) -> list of strings\n\ 775\n\ 776Return an alphabetized list of names comprising (some of) the attributes\n\ 777of the given object. Without an argument, the names in the current scope\n\ 778are listed. With an instance argument, only the instance attributes are\n\ 779returned. With a class argument, attributes of the base class are not\n\ 780returned. For other types or arguments, this may list members or methods."; 781 782 783static PyObject * 784builtin_divmod(self, args) 785 PyObject *self; 786 PyObject *args; 787{ 788 PyObject *v, *w; 789 790 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w)) 791 return NULL; 792 return PyNumber_Divmod(v, w); 793} 794 795static char divmod_doc[] = 796"divmod(x, y) -> (div, mod)\n\ 797\n\ 798Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x."; 799 800 801static PyObject * 802builtin_eval(self, args) 803 PyObject *self; 804 PyObject *args; 805{ 806 PyObject *cmd; 807 PyObject *globals = Py_None, *locals = Py_None; 808 char *str; 809 810 if (!PyArg_ParseTuple(args, "O|O!O!:eval", 811 &cmd, 812 &PyDict_Type, &globals, 813 &PyDict_Type, &locals)) 814 return NULL; 815 if (globals == Py_None) { 816 globals = PyEval_GetGlobals(); 817 if (locals == Py_None) 818 locals = PyEval_GetLocals(); 819 } 820 else if (locals == Py_None) 821 locals = globals; 822 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 823 if (PyDict_SetItemString(globals, "__builtins__", 824 PyEval_GetBuiltins()) != 0) 825 return NULL; 826 } 827 if (PyCode_Check(cmd)) 828 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); 829 if (!PyString_Check(cmd)) { 830 PyErr_SetString(PyExc_TypeError, 831 "eval() argument 1 must be string or code object"); 832 return NULL; 833 } 834 str = PyString_AsString(cmd); 835 if ((int)strlen(str) != PyString_Size(cmd)) { 836 PyErr_SetString(PyExc_ValueError, 837 "embedded '\\0' in string arg"); 838 return NULL; 839 } 840 while (*str == ' ' || *str == '\t') 841 str++; 842 return PyRun_String(str, Py_eval_input, globals, locals); 843} 844 845static char eval_doc[] = 846"eval(source[, globals[, locals]]) -> value\n\ 847\n\ 848Evaluate the source in the context of globals and locals.\n\ 849The source may be a string representing a Python expression\n\ 850or a code object as returned by compile().\n\ 851The globals and locals are dictionaries, defaulting to the current\n\ 852globals and locals. If only globals is given, locals defaults to it."; 853 854 855static PyObject * 856builtin_execfile(self, args) 857 PyObject *self; 858 PyObject *args; 859{ 860 char *filename; 861 PyObject *globals = Py_None, *locals = Py_None; 862 PyObject *res; 863 FILE* fp; 864 865 if (!PyArg_ParseTuple(args, "s|O!O!:execfile", 866 &filename, 867 &PyDict_Type, &globals, 868 &PyDict_Type, &locals)) 869 return NULL; 870 if (globals == Py_None) { 871 globals = PyEval_GetGlobals(); 872 if (locals == Py_None) 873 locals = PyEval_GetLocals(); 874 } 875 else if (locals == Py_None) 876 locals = globals; 877 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 878 if (PyDict_SetItemString(globals, "__builtins__", 879 PyEval_GetBuiltins()) != 0) 880 return NULL; 881 } 882 Py_BEGIN_ALLOW_THREADS 883 fp = fopen(filename, "r"); 884 Py_END_ALLOW_THREADS 885 if (fp == NULL) { 886 PyErr_SetFromErrno(PyExc_IOError); 887 return NULL; 888 } 889 res = PyRun_File(fp, filename, Py_file_input, globals, locals); 890 Py_BEGIN_ALLOW_THREADS 891 fclose(fp); 892 Py_END_ALLOW_THREADS 893 return res; 894} 895 896static char execfile_doc[] = 897"execfile(filename[, globals[, locals]])\n\ 898\n\ 899Read and execute a Python script from a file.\n\ 900The globals and locals are dictionaries, defaulting to the current\n\ 901globals and locals. If only globals is given, locals defaults to it."; 902 903 904static PyObject * 905builtin_getattr(self, args) 906 PyObject *self; 907 PyObject *args; 908{ 909 PyObject *v, *result, *dflt = NULL; 910 PyObject *name; 911 912 if (!PyArg_ParseTuple(args, "OS|O:getattr", &v, &name, &dflt)) 913 return NULL; 914 result = PyObject_GetAttr(v, name); 915 if (result == NULL && dflt != NULL) { 916 PyErr_Clear(); 917 Py_INCREF(dflt); 918 result = dflt; 919 } 920 return result; 921} 922 923static char getattr_doc[] = 924"getattr(object, name[, default]) -> value\n\ 925\n\ 926Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\ 927When a default argument is given, it is returned when the attribute doesn't\n\ 928exist; without it, an exception is raised in that case."; 929 930 931static PyObject * 932builtin_globals(self, args) 933 PyObject *self; 934 PyObject *args; 935{ 936 PyObject *d; 937 938 if (!PyArg_ParseTuple(args, ":globals")) 939 return NULL; 940 d = PyEval_GetGlobals(); 941 Py_INCREF(d); 942 return d; 943} 944 945static char globals_doc[] = 946"globals() -> dictionary\n\ 947\n\ 948Return the dictionary containing the current scope's global variables."; 949 950 951static PyObject * 952builtin_hasattr(self, args) 953 PyObject *self; 954 PyObject *args; 955{ 956 PyObject *v; 957 PyObject *name; 958 959 if (!PyArg_ParseTuple(args, "OS:hasattr", &v, &name)) 960 return NULL; 961 v = PyObject_GetAttr(v, name); 962 if (v == NULL) { 963 PyErr_Clear(); 964 Py_INCREF(Py_False); 965 return Py_False; 966 } 967 Py_DECREF(v); 968 Py_INCREF(Py_True); 969 return Py_True; 970} 971 972static char hasattr_doc[] = 973"hasattr(object, name) -> Boolean\n\ 974\n\ 975Return whether the object has an attribute with the given name.\n\ 976(This is done by calling getattr(object, name) and catching exceptions.)"; 977 978 979static PyObject * 980builtin_id(self, args) 981 PyObject *self; 982 PyObject *args; 983{ 984 PyObject *v; 985 986 if (!PyArg_ParseTuple(args, "O:id", &v)) 987 return NULL; 988 return PyInt_FromLong((long)v); 989} 990 991static char id_doc[] = 992"id(object) -> integer\n\ 993\n\ 994Return the identity of an object. This is guaranteed to be unique among\n\ 995simultaneously existing objects. (Hint: it's the object's memory address.)"; 996 997 998static PyObject * 999builtin_map(self, args) 1000 PyObject *self; 1001 PyObject *args; 1002{ 1003 typedef struct { 1004 PyObject *seq; 1005 PySequenceMethods *sqf; 1006 int len; 1007 } sequence; 1008 1009 PyObject *func, *result; 1010 sequence *seqs = NULL, *sqp; 1011 int n, len; 1012 register int i, j; 1013 1014 n = PyTuple_Size(args); 1015 if (n < 2) { 1016 PyErr_SetString(PyExc_TypeError, 1017 "map() requires at least two args"); 1018 return NULL; 1019 } 1020 1021 func = PyTuple_GetItem(args, 0); 1022 n--; 1023 1024 if (func == Py_None && n == 1) { 1025 /* map(None, S) is the same as list(S). */ 1026 return PySequence_List(PyTuple_GetItem(args, 1)); 1027 } 1028 1029 if ((seqs = PyMem_NEW(sequence, n)) == NULL) { 1030 PyErr_NoMemory(); 1031 goto Fail_2; 1032 } 1033 1034 for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) { 1035 int curlen; 1036 PySequenceMethods *sqf; 1037 1038 if ((sqp->seq = PyTuple_GetItem(args, i + 1)) == NULL) 1039 goto Fail_2; 1040 1041 sqp->sqf = sqf = sqp->seq->ob_type->tp_as_sequence; 1042 if (sqf == NULL || 1043 sqf->sq_length == NULL || 1044 sqf->sq_item == NULL) 1045 { 1046 static char errmsg[] = 1047 "argument %d to map() must be a sequence object"; 1048 char errbuf[sizeof(errmsg) + 25]; 1049 1050 sprintf(errbuf, errmsg, i+2); 1051 PyErr_SetString(PyExc_TypeError, errbuf); 1052 goto Fail_2; 1053 } 1054 1055 if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0) 1056 goto Fail_2; 1057 1058 if (curlen > len) 1059 len = curlen; 1060 } 1061 1062 if ((result = (PyObject *) PyList_New(len)) == NULL) 1063 goto Fail_2; 1064 1065 for (i = 0; ; ++i) { 1066 PyObject *alist, *item=NULL, *value; 1067 int any = 0; 1068 1069 if (func == Py_None && n == 1) 1070 alist = NULL; 1071 else { 1072 if ((alist = PyTuple_New(n)) == NULL) 1073 goto Fail_1; 1074 } 1075 1076 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) { 1077 if (sqp->len < 0) { 1078 Py_INCREF(Py_None); 1079 item = Py_None; 1080 } 1081 else { 1082 item = (*sqp->sqf->sq_item)(sqp->seq, i); 1083 if (item == NULL) { 1084 if (PyErr_ExceptionMatches( 1085 PyExc_IndexError)) 1086 { 1087 PyErr_Clear(); 1088 Py_INCREF(Py_None); 1089 item = Py_None; 1090 sqp->len = -1; 1091 } 1092 else { 1093 goto Fail_0; 1094 } 1095 } 1096 else 1097 any = 1; 1098 1099 } 1100 if (!alist) 1101 break; 1102 if (PyTuple_SetItem(alist, j, item) < 0) { 1103 Py_DECREF(item); 1104 goto Fail_0; 1105 } 1106 continue; 1107 1108 Fail_0: 1109 Py_XDECREF(alist); 1110 goto Fail_1; 1111 } 1112 1113 if (!alist) 1114 alist = item; 1115 1116 if (!any) { 1117 Py_DECREF(alist); 1118 break; 1119 } 1120 1121 if (func == Py_None) 1122 value = alist; 1123 else { 1124 value = PyEval_CallObject(func, alist); 1125 Py_DECREF(alist); 1126 if (value == NULL) 1127 goto Fail_1; 1128 } 1129 if (i >= len) { 1130 int status = PyList_Append(result, value); 1131 Py_DECREF(value); 1132 if (status < 0) 1133 goto Fail_1; 1134 } 1135 else { 1136 if (PyList_SetItem(result, i, value) < 0) 1137 goto Fail_1; 1138 } 1139 } 1140 1141 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0) 1142 goto Fail_1; 1143 1144 PyMem_DEL(seqs); 1145 return result; 1146 1147Fail_1: 1148 Py_DECREF(result); 1149Fail_2: 1150 if (seqs) PyMem_DEL(seqs); 1151 return NULL; 1152} 1153 1154static char map_doc[] = 1155"map(function, sequence[, sequence, ...]) -> list\n\ 1156\n\ 1157Return a list of the results of applying the function to the items of\n\ 1158the argument sequence(s). If more than one sequence is given, the\n\ 1159function is called with an argument list consisting of the corresponding\n\ 1160item of each sequence, substituting None for missing values when not all\n\ 1161sequences have the same length. If the function is None, return a list of\n\ 1162the items of the sequence (or a list of tuples if more than one sequence)."; 1163 1164 1165static PyObject * 1166builtin_setattr(self, args) 1167 PyObject *self; 1168 PyObject *args; 1169{ 1170 PyObject *v; 1171 PyObject *name; 1172 PyObject *value; 1173 1174 if (!PyArg_ParseTuple(args, "OSO:setattr", &v, &name, &value)) 1175 return NULL; 1176 if (PyObject_SetAttr(v, name, value) != 0) 1177 return NULL; 1178 Py_INCREF(Py_None); 1179 return Py_None; 1180} 1181 1182static char setattr_doc[] = 1183"setattr(object, name, value)\n\ 1184\n\ 1185Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\ 1186``x.y = v''."; 1187 1188 1189static PyObject * 1190builtin_delattr(self, args) 1191 PyObject *self; 1192 PyObject *args; 1193{ 1194 PyObject *v; 1195 PyObject *name; 1196 1197 if (!PyArg_ParseTuple(args, "OS:delattr", &v, &name)) 1198 return NULL; 1199 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) 1200 return NULL; 1201 Py_INCREF(Py_None); 1202 return Py_None; 1203} 1204 1205static char delattr_doc[] = 1206"delattr(object, name)\n\ 1207\n\ 1208Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\ 1209``del x.y''."; 1210 1211 1212static PyObject * 1213builtin_hash(self, args) 1214 PyObject *self; 1215 PyObject *args; 1216{ 1217 PyObject *v; 1218 long x; 1219 1220 if (!PyArg_ParseTuple(args, "O:hash", &v)) 1221 return NULL; 1222 x = PyObject_Hash(v); 1223 if (x == -1) 1224 return NULL; 1225 return PyInt_FromLong(x); 1226} 1227 1228static char hash_doc[] = 1229"hash(object) -> integer\n\ 1230\n\ 1231Return a hash value for the object. Two objects with the same value have\n\ 1232the same hash value. The reverse is not necessarily true, but likely."; 1233 1234 1235static PyObject * 1236builtin_hex(self, args) 1237 PyObject *self; 1238 PyObject *args; 1239{ 1240 PyObject *v; 1241 PyNumberMethods *nb; 1242 1243 if (!PyArg_ParseTuple(args, "O:hex", &v)) 1244 return NULL; 1245 1246 if ((nb = v->ob_type->tp_as_number) == NULL || 1247 nb->nb_hex == NULL) { 1248 PyErr_SetString(PyExc_TypeError, 1249 "hex() argument can't be converted to hex"); 1250 return NULL; 1251 } 1252 return (*nb->nb_hex)(v); 1253} 1254 1255static char hex_doc[] = 1256"hex(number) -> string\n\ 1257\n\ 1258Return the hexadecimal representation of an integer or long integer."; 1259 1260 1261static PyObject *builtin_raw_input Py_PROTO((PyObject *, PyObject *)); 1262 1263static PyObject * 1264builtin_input(self, args) 1265 PyObject *self; 1266 PyObject *args; 1267{ 1268 PyObject *line; 1269 char *str; 1270 PyObject *res; 1271 PyObject *globals, *locals; 1272 1273 line = builtin_raw_input(self, args); 1274 if (line == NULL) 1275 return line; 1276 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str)) 1277 return NULL; 1278 while (*str == ' ' || *str == '\t') 1279 str++; 1280 globals = PyEval_GetGlobals(); 1281 locals = PyEval_GetLocals(); 1282 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { 1283 if (PyDict_SetItemString(globals, "__builtins__", 1284 PyEval_GetBuiltins()) != 0) 1285 return NULL; 1286 } 1287 res = PyRun_String(str, Py_eval_input, globals, locals); 1288 Py_DECREF(line); 1289 return res; 1290} 1291 1292static char input_doc[] = 1293"input([prompt]) -> value\n\ 1294\n\ 1295Equivalent to eval(raw_input(prompt))."; 1296 1297 1298static PyObject * 1299builtin_intern(self, args) 1300 PyObject *self; 1301 PyObject *args; 1302{ 1303 PyObject *s; 1304 if (!PyArg_ParseTuple(args, "S:intern", &s)) 1305 return NULL; 1306 Py_INCREF(s); 1307 PyString_InternInPlace(&s); 1308 return s; 1309} 1310 1311static char intern_doc[] = 1312"intern(string) -> string\n\ 1313\n\ 1314``Intern'' the given string. This enters the string in the (global)\n\ 1315table of interned strings whose purpose is to speed up dictionary lookups.\n\ 1316Return the string itself or the previously interned string object with the\n\ 1317same value."; 1318 1319 1320static PyObject * 1321builtin_int(self, args) 1322 PyObject *self; 1323 PyObject *args; 1324{ 1325 PyObject *v; 1326 int base = -909; /* unlikely! */ 1327 1328 if (!PyArg_ParseTuple(args, "O|i:int", &v, &base)) 1329 return NULL; 1330 if (base == -909) 1331 return PyNumber_Int(v); 1332 else if (PyString_Check(v)) 1333 return PyInt_FromString(PyString_AS_STRING(v), NULL, base); 1334 else if (PyUnicode_Check(v)) 1335 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(v), 1336 PyUnicode_GET_SIZE(v), 1337 base); 1338 else { 1339 PyErr_SetString(PyExc_TypeError, 1340 "can't convert non-string with explicit base"); 1341 return NULL; 1342 } 1343} 1344 1345static char int_doc[] = 1346"int(x[, base]) -> integer\n\ 1347\n\ 1348Convert a string or number to an integer, if possible. A floating point\n\ 1349argument will be truncated towards zero (this does not include a string\n\ 1350representation of a floating point number!) When converting a string, use\n\ 1351the optional base. It is an error to supply a base when converting a\n\ 1352non-string."; 1353 1354 1355static PyObject * 1356builtin_long(self, args) 1357 PyObject *self; 1358 PyObject *args; 1359{ 1360 PyObject *v; 1361 int base = -909; /* unlikely! */ 1362 1363 if (!PyArg_ParseTuple(args, "O|i:long", &v, &base)) 1364 return NULL; 1365 if (base == -909) 1366 return PyNumber_Long(v); 1367 else if (PyString_Check(v)) 1368 return PyLong_FromString(PyString_AS_STRING(v), NULL, base); 1369 else if (PyUnicode_Check(v)) 1370 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(v), 1371 PyUnicode_GET_SIZE(v), 1372 base); 1373 else { 1374 PyErr_SetString(PyExc_TypeError, 1375 "can't convert non-string with explicit base"); 1376 return NULL; 1377 } 1378} 1379 1380static char long_doc[] = 1381"long(x) -> long integer\n\ 1382long(x, base) -> long integer\n\ 1383\n\ 1384Convert a string or number to a long integer, if possible. A floating\n\ 1385point argument will be truncated towards zero (this does not include a\n\ 1386string representation of a floating point number!) When converting a\n\ 1387string, use the given base. It is an error to supply a base when\n\ 1388converting a non-string."; 1389 1390 1391static PyObject * 1392builtin_float(self, args) 1393 PyObject *self; 1394 PyObject *args; 1395{ 1396 PyObject *v; 1397 1398 if (!PyArg_ParseTuple(args, "O:float", &v)) 1399 return NULL; 1400 if (PyString_Check(v)) 1401 return PyFloat_FromString(v, NULL); 1402 return PyNumber_Float(v); 1403} 1404 1405static char float_doc[] = 1406"float(x) -> floating point number\n\ 1407\n\ 1408Convert a string or number to a floating point number, if possible."; 1409 1410 1411static PyObject * 1412builtin_len(self, args) 1413 PyObject *self; 1414 PyObject *args; 1415{ 1416 PyObject *v; 1417 long res; 1418 1419 if (!PyArg_ParseTuple(args, "O:len", &v)) 1420 return NULL; 1421 res = PyObject_Length(v); 1422 if (res < 0 && PyErr_Occurred()) 1423 return NULL; 1424 return PyInt_FromLong(res); 1425} 1426 1427static char len_doc[] = 1428"len(object) -> integer\n\ 1429\n\ 1430Return the number of items of a sequence or mapping."; 1431 1432 1433static PyObject * 1434builtin_list(self, args) 1435 PyObject *self; 1436 PyObject *args; 1437{ 1438 PyObject *v; 1439 1440 if (!PyArg_ParseTuple(args, "O:list", &v)) 1441 return NULL; 1442 return PySequence_List(v); 1443} 1444 1445static char list_doc[] = 1446"list(sequence) -> list\n\ 1447\n\ 1448Return a new list whose items are the same as those of the argument sequence."; 1449 1450 1451static PyObject * 1452builtin_slice(self, args) 1453 PyObject *self; 1454 PyObject *args; 1455{ 1456 PyObject *start, *stop, *step; 1457 1458 start = stop = step = NULL; 1459 1460 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step)) 1461 return NULL; 1462 1463 /* This swapping of stop and start is to maintain similarity with 1464 range(). */ 1465 if (stop == NULL) { 1466 stop = start; 1467 start = NULL; 1468 } 1469 return PySlice_New(start, stop, step); 1470} 1471 1472static char slice_doc[] = 1473"slice([start,] stop[, step]) -> slice object\n\ 1474\n\ 1475Create a slice object. This is used for slicing by the Numeric extensions."; 1476 1477 1478static PyObject * 1479builtin_locals(self, args) 1480 PyObject *self; 1481 PyObject *args; 1482{ 1483 PyObject *d; 1484 1485 if (!PyArg_ParseTuple(args, ":locals")) 1486 return NULL; 1487 d = PyEval_GetLocals(); 1488 Py_INCREF(d); 1489 return d; 1490} 1491 1492static char locals_doc[] = 1493"locals() -> dictionary\n\ 1494\n\ 1495Return the dictionary containing the current scope's local variables."; 1496 1497 1498static PyObject * 1499min_max(args, sign) 1500 PyObject *args; 1501 int sign; 1502{ 1503 int i; 1504 PyObject *v, *w, *x; 1505 PySequenceMethods *sq; 1506 1507 if (PyTuple_Size(args) > 1) 1508 v = args; 1509 else if (!PyArg_ParseTuple(args, "O:min/max", &v)) 1510 return NULL; 1511 sq = v->ob_type->tp_as_sequence; 1512 if (sq == NULL || sq->sq_item == NULL) { 1513 PyErr_SetString(PyExc_TypeError, 1514 "min() or max() of non-sequence"); 1515 return NULL; 1516 } 1517 w = NULL; 1518 for (i = 0; ; i++) { 1519 x = (*sq->sq_item)(v, i); /* Implies INCREF */ 1520 if (x == NULL) { 1521 if (PyErr_ExceptionMatches(PyExc_IndexError)) { 1522 PyErr_Clear(); 1523 break; 1524 } 1525 Py_XDECREF(w); 1526 return NULL; 1527 } 1528 if (w == NULL) 1529 w = x; 1530 else { 1531 int c = PyObject_Compare(x, w); 1532 if (c && PyErr_Occurred()) { 1533 Py_DECREF(x); 1534 Py_XDECREF(w); 1535 return NULL; 1536 } 1537 if (c * sign > 0) { 1538 Py_DECREF(w); 1539 w = x; 1540 } 1541 else 1542 Py_DECREF(x); 1543 } 1544 } 1545 if (w == NULL) 1546 PyErr_SetString(PyExc_ValueError, 1547 "min() or max() of empty sequence"); 1548 return w; 1549} 1550 1551static PyObject * 1552builtin_min(self, v) 1553 PyObject *self; 1554 PyObject *v; 1555{ 1556 return min_max(v, -1); 1557} 1558 1559static char min_doc[] = 1560"min(sequence) -> value\n\ 1561min(a, b, c, ...) -> value\n\ 1562\n\ 1563With a single sequence argument, return its smallest item.\n\ 1564With two or more arguments, return the smallest argument."; 1565 1566 1567static PyObject * 1568builtin_max(self, v) 1569 PyObject *self; 1570 PyObject *v; 1571{ 1572 return min_max(v, 1); 1573} 1574 1575static char max_doc[] = 1576"max(sequence) -> value\n\ 1577max(a, b, c, ...) -> value\n\ 1578\n\ 1579With a single sequence argument, return its largest item.\n\ 1580With two or more arguments, return the largest argument."; 1581 1582 1583static PyObject * 1584builtin_oct(self, args) 1585 PyObject *self; 1586 PyObject *args; 1587{ 1588 PyObject *v; 1589 PyNumberMethods *nb; 1590 1591 if (!PyArg_ParseTuple(args, "O:oct", &v)) 1592 return NULL; 1593 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL || 1594 nb->nb_oct == NULL) { 1595 PyErr_SetString(PyExc_TypeError, 1596 "oct() argument can't be converted to oct"); 1597 return NULL; 1598 } 1599 return (*nb->nb_oct)(v); 1600} 1601 1602static char oct_doc[] = 1603"oct(number) -> string\n\ 1604\n\ 1605Return the octal representation of an integer or long integer."; 1606 1607 1608static PyObject * 1609builtin_open(self, args) 1610 PyObject *self; 1611 PyObject *args; 1612{ 1613 char *name; 1614 char *mode = "r"; 1615 int bufsize = -1; 1616 PyObject *f; 1617 1618 if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize)) 1619 return NULL; 1620 f = PyFile_FromString(name, mode); 1621 if (f != NULL) 1622 PyFile_SetBufSize(f, bufsize); 1623 return f; 1624} 1625 1626static char open_doc[] = 1627"open(filename[, mode[, buffering]]) -> file object\n\ 1628\n\ 1629Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\ 1630writing or appending. The file will be created if it doesn't exist\n\ 1631when opened for writing or appending; it will be truncated when\n\ 1632opened for writing. Add a 'b' to the mode for binary files.\n\ 1633Add a '+' to the mode to allow simultaneous reading and writing.\n\ 1634If the buffering argument is given, 0 means unbuffered, 1 means line\n\ 1635buffered, and larger numbers specify the buffer size."; 1636 1637 1638static PyObject * 1639builtin_ord(self, args) 1640 PyObject *self; 1641 PyObject *args; 1642{ 1643 PyObject *obj; 1644 long ord; 1645 int size; 1646 1647 if (!PyArg_ParseTuple(args, "O:ord", &obj)) 1648 return NULL; 1649 1650 if (PyString_Check(obj)) { 1651 size = PyString_GET_SIZE(obj); 1652 if (size == 1) 1653 ord = (long)((unsigned char)*PyString_AS_STRING(obj)); 1654 } else if (PyUnicode_Check(obj)) { 1655 size = PyUnicode_GET_SIZE(obj); 1656 if (size == 1) 1657 ord = (long)*PyUnicode_AS_UNICODE(obj); 1658 } else { 1659 PyErr_Format(PyExc_TypeError, 1660 "expected string or Unicode character, " \ 1661 "%.200s found", obj->ob_type->tp_name); 1662 return NULL; 1663 } 1664 if (size == 1) 1665 return PyInt_FromLong(ord); 1666 1667 PyErr_Format(PyExc_TypeError, 1668 "expected a character, length-%d string found", 1669 size); 1670 return NULL; 1671} 1672 1673static char ord_doc[] = 1674"ord(c) -> integer\n\ 1675\n\ 1676Return the integer ordinal of a one character string."; 1677 1678 1679static PyObject * 1680builtin_pow(self, args) 1681 PyObject *self; 1682 PyObject *args; 1683{ 1684 PyObject *v, *w, *z = Py_None; 1685 1686 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z)) 1687 return NULL; 1688 return PyNumber_Power(v, w, z); 1689} 1690 1691static char pow_doc[] = 1692"pow(x, y[, z]) -> number\n\ 1693\n\ 1694With two arguments, equivalent to x**y. With three arguments,\n\ 1695equivalent to (x**y) % z, but may be more efficient (e.g. for longs)."; 1696 1697 1698/* Return number of items in range/xrange (lo, hi, step). step > 0 1699 * required. Return a value < 0 if & only if the true value is too 1700 * large to fit in a signed long. 1701 */ 1702static long 1703get_len_of_range(lo, hi, step) 1704 long lo; 1705 long hi; 1706 long step; /* must be > 0 */ 1707{ 1708 /* ------------------------------------------------------------- 1709 If lo >= hi, the range is empty. 1710 Else if n values are in the range, the last one is 1711 lo + (n-1)*step, which must be <= hi-1. Rearranging, 1712 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives 1713 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so 1714 the RHS is non-negative and so truncation is the same as the 1715 floor. Letting M be the largest positive long, the worst case 1716 for the RHS numerator is hi=M, lo=-M-1, and then 1717 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough 1718 precision to compute the RHS exactly. 1719 ---------------------------------------------------------------*/ 1720 long n = 0; 1721 if (lo < hi) { 1722 unsigned long uhi = (unsigned long)hi; 1723 unsigned long ulo = (unsigned long)lo; 1724 unsigned long diff = uhi - ulo - 1; 1725 n = (long)(diff / (unsigned long)step + 1); 1726 } 1727 return n; 1728} 1729 1730static PyObject * 1731builtin_range(self, args) 1732 PyObject *self; 1733 PyObject *args; 1734{ 1735 long ilow = 0, ihigh = 0, istep = 1; 1736 long bign; 1737 int i, n; 1738 1739 PyObject *v; 1740 1741 if (PyTuple_Size(args) <= 1) { 1742 if (!PyArg_ParseTuple(args, 1743 "l;range() requires 1-3 int arguments", 1744 &ihigh)) 1745 return NULL; 1746 } 1747 else { 1748 if (!PyArg_ParseTuple(args, 1749 "ll|l;range() requires 1-3 int arguments", 1750 &ilow, &ihigh, &istep)) 1751 return NULL; 1752 } 1753 if (istep == 0) { 1754 PyErr_SetString(PyExc_ValueError, "zero step for range()"); 1755 return NULL; 1756 } 1757 if (istep > 0) 1758 bign = get_len_of_range(ilow, ihigh, istep); 1759 else 1760 bign = get_len_of_range(ihigh, ilow, -istep); 1761 n = (int)bign; 1762 if (bign < 0 || (long)n != bign) { 1763 PyErr_SetString(PyExc_OverflowError, 1764 "range() has too many items"); 1765 return NULL; 1766 } 1767 v = PyList_New(n); 1768 if (v == NULL) 1769 return NULL; 1770 for (i = 0; i < n; i++) { 1771 PyObject *w = PyInt_FromLong(ilow); 1772 if (w == NULL) { 1773 Py_DECREF(v); 1774 return NULL; 1775 } 1776 PyList_SET_ITEM(v, i, w); 1777 ilow += istep; 1778 } 1779 return v; 1780} 1781 1782static char range_doc[] = 1783"range([start,] stop[, step]) -> list of integers\n\ 1784\n\ 1785Return a list containing an arithmetic progression of integers.\n\ 1786range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\ 1787When step is given, it specifies the increment (or decrement).\n\ 1788For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\ 1789These are exactly the valid indices for a list of 4 elements."; 1790 1791 1792static PyObject * 1793builtin_xrange(self, args) 1794 PyObject *self; 1795 PyObject *args; 1796{ 1797 long ilow = 0, ihigh = 0, istep = 1; 1798 long n; 1799 1800 if (PyTuple_Size(args) <= 1) { 1801 if (!PyArg_ParseTuple(args, 1802 "l;xrange() requires 1-3 int arguments", 1803 &ihigh)) 1804 return NULL; 1805 } 1806 else { 1807 if (!PyArg_ParseTuple(args, 1808 "ll|l;xrange() requires 1-3 int arguments", 1809 &ilow, &ihigh, &istep)) 1810 return NULL; 1811 } 1812 if (istep == 0) { 1813 PyErr_SetString(PyExc_ValueError, "zero step for xrange()"); 1814 return NULL; 1815 } 1816 if (istep > 0) 1817 n = get_len_of_range(ilow, ihigh, istep); 1818 else 1819 n = get_len_of_range(ihigh, ilow, -istep); 1820 if (n < 0) { 1821 PyErr_SetString(PyExc_OverflowError, 1822 "xrange() has more than sys.maxint items"); 1823 return NULL; 1824 } 1825 return PyRange_New(ilow, n, istep, 1); 1826} 1827 1828static char xrange_doc[] = 1829"xrange([start,] stop[, step]) -> xrange object\n\ 1830\n\ 1831Like range(), but instead of returning a list, returns an object that\n\ 1832generates the numbers in the range on demand. This is slightly slower\n\ 1833than range() but more memory efficient."; 1834 1835 1836static PyObject * 1837builtin_raw_input(self, args) 1838 PyObject *self; 1839 PyObject *args; 1840{ 1841 PyObject *v = NULL; 1842 PyObject *f; 1843 1844 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v)) 1845 return NULL; 1846 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin && 1847 PyFile_AsFile(PySys_GetObject("stdout")) == stdout && 1848 isatty(fileno(stdin)) && isatty(fileno(stdout))) { 1849 PyObject *po; 1850 char *prompt; 1851 char *s; 1852 PyObject *result; 1853 if (v != NULL) { 1854 po = PyObject_Str(v); 1855 if (po == NULL) 1856 return NULL; 1857 prompt = PyString_AsString(po); 1858 if (prompt == NULL) 1859 return NULL; 1860 } 1861 else { 1862 po = NULL; 1863 prompt = ""; 1864 } 1865 s = PyOS_Readline(prompt); 1866 Py_XDECREF(po); 1867 if (s == NULL) { 1868 PyErr_SetNone(PyExc_KeyboardInterrupt); 1869 return NULL; 1870 } 1871 if (*s == '\0') { 1872 PyErr_SetNone(PyExc_EOFError); 1873 result = NULL; 1874 } 1875 else { /* strip trailing '\n' */ 1876 result = PyString_FromStringAndSize(s, strlen(s)-1); 1877 } 1878 PyMem_FREE(s); 1879 return result; 1880 } 1881 if (v != NULL) { 1882 f = PySys_GetObject("stdout"); 1883 if (f == NULL) { 1884 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); 1885 return NULL; 1886 } 1887 if (Py_FlushLine() != 0 || 1888 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0) 1889 return NULL; 1890 } 1891 f = PySys_GetObject("stdin"); 1892 if (f == NULL) { 1893 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin"); 1894 return NULL; 1895 } 1896 return PyFile_GetLine(f, -1); 1897} 1898 1899static char raw_input_doc[] = 1900"raw_input([prompt]) -> string\n\ 1901\n\ 1902Read a string from standard input. The trailing newline is stripped.\n\ 1903If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\ 1904On Unix, GNU readline is used if enabled. The prompt string, if given,\n\ 1905is printed without a trailing newline before reading."; 1906 1907 1908static PyObject * 1909builtin_reduce(self, args) 1910 PyObject *self; 1911 PyObject *args; 1912{ 1913 PyObject *seq, *func, *result = NULL; 1914 PySequenceMethods *sqf; 1915 register int i; 1916 1917 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result)) 1918 return NULL; 1919 if (result != NULL) 1920 Py_INCREF(result); 1921 1922 sqf = seq->ob_type->tp_as_sequence; 1923 if (sqf == NULL || sqf->sq_item == NULL) { 1924 PyErr_SetString(PyExc_TypeError, 1925 "2nd argument to reduce() must be a sequence object"); 1926 return NULL; 1927 } 1928 1929 if ((args = PyTuple_New(2)) == NULL) 1930 goto Fail; 1931 1932 for (i = 0; ; ++i) { 1933 PyObject *op2; 1934 1935 if (args->ob_refcnt > 1) { 1936 Py_DECREF(args); 1937 if ((args = PyTuple_New(2)) == NULL) 1938 goto Fail; 1939 } 1940 1941 if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) { 1942 if (PyErr_ExceptionMatches(PyExc_IndexError)) { 1943 PyErr_Clear(); 1944 break; 1945 } 1946 goto Fail; 1947 } 1948 1949 if (result == NULL) 1950 result = op2; 1951 else { 1952 PyTuple_SetItem(args, 0, result); 1953 PyTuple_SetItem(args, 1, op2); 1954 if ((result = PyEval_CallObject(func, args)) == NULL) 1955 goto Fail; 1956 } 1957 } 1958 1959 Py_DECREF(args); 1960 1961 if (result == NULL) 1962 PyErr_SetString(PyExc_TypeError, 1963 "reduce of empty sequence with no initial value"); 1964 1965 return result; 1966 1967Fail: 1968 Py_XDECREF(args); 1969 Py_XDECREF(result); 1970 return NULL; 1971} 1972 1973static char reduce_doc[] = 1974"reduce(function, sequence[, initial]) -> value\n\ 1975\n\ 1976Apply a function of two arguments cumulatively to the items of a sequence,\n\ 1977from left to right, so as to reduce the sequence to a single value.\n\ 1978For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\ 1979((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\ 1980of the sequence in the calculation, and serves as a default when the\n\ 1981sequence is empty."; 1982 1983 1984static PyObject * 1985builtin_reload(self, args) 1986 PyObject *self; 1987 PyObject *args; 1988{ 1989 PyObject *v; 1990 1991 if (!PyArg_ParseTuple(args, "O:reload", &v)) 1992 return NULL; 1993 return PyImport_ReloadModule(v); 1994} 1995 1996static char reload_doc[] = 1997"reload(module) -> module\n\ 1998\n\ 1999Reload the module. The module must have been successfully imported before."; 2000 2001 2002static PyObject * 2003builtin_repr(self, args) 2004 PyObject *self; 2005 PyObject *args; 2006{ 2007 PyObject *v; 2008 2009 if (!PyArg_ParseTuple(args, "O:repr", &v)) 2010 return NULL; 2011 return PyObject_Repr(v); 2012} 2013 2014static char repr_doc[] = 2015"repr(object) -> string\n\ 2016\n\ 2017Return the canonical string representation of the object.\n\ 2018For most object types, eval(repr(object)) == object."; 2019 2020 2021static PyObject * 2022builtin_round(self, args) 2023 PyObject *self; 2024 PyObject *args; 2025{ 2026 double x; 2027 double f; 2028 int ndigits = 0; 2029 int i; 2030 2031 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits)) 2032 return NULL; 2033 f = 1.0; 2034 i = abs(ndigits); 2035 while (--i >= 0) 2036 f = f*10.0; 2037 if (ndigits < 0) 2038 x /= f; 2039 else 2040 x *= f; 2041 if (x >= 0.0) 2042 x = floor(x + 0.5); 2043 else 2044 x = ceil(x - 0.5); 2045 if (ndigits < 0) 2046 x *= f; 2047 else 2048 x /= f; 2049 return PyFloat_FromDouble(x); 2050} 2051 2052static char round_doc[] = 2053"round(number[, ndigits]) -> floating point number\n\ 2054\n\ 2055Round a number to a given precision in decimal digits (default 0 digits).\n\ 2056This always returns a floating point number. Precision may be negative."; 2057 2058 2059static PyObject * 2060builtin_str(self, args) 2061 PyObject *self; 2062 PyObject *args; 2063{ 2064 PyObject *v; 2065 2066 if (!PyArg_ParseTuple(args, "O:str", &v)) 2067 return NULL; 2068 return PyObject_Str(v); 2069} 2070 2071static char str_doc[] = 2072"str(object) -> string\n\ 2073\n\ 2074Return a nice string representation of the object.\n\ 2075If the argument is a string, the return value is the same object."; 2076 2077 2078static PyObject * 2079builtin_tuple(self, args) 2080 PyObject *self; 2081 PyObject *args; 2082{ 2083 PyObject *v; 2084 2085 if (!PyArg_ParseTuple(args, "O:tuple", &v)) 2086 return NULL; 2087 return PySequence_Tuple(v); 2088} 2089 2090static char tuple_doc[] = 2091"tuple(sequence) -> list\n\ 2092\n\ 2093Return a tuple whose items are the same as those of the argument sequence.\n\ 2094If the argument is a tuple, the return value is the same object."; 2095 2096 2097static PyObject * 2098builtin_type(self, args) 2099 PyObject *self; 2100 PyObject *args; 2101{ 2102 PyObject *v; 2103 2104 if (!PyArg_ParseTuple(args, "O:type", &v)) 2105 return NULL; 2106 v = (PyObject *)v->ob_type; 2107 Py_INCREF(v); 2108 return v; 2109} 2110 2111static char type_doc[] = 2112"type(object) -> type object\n\ 2113\n\ 2114Return the type of the object."; 2115 2116 2117static PyObject * 2118builtin_vars(self, args) 2119 PyObject *self; 2120 PyObject *args; 2121{ 2122 PyObject *v = NULL; 2123 PyObject *d; 2124 2125 if (!PyArg_ParseTuple(args, "|O:vars", &v)) 2126 return NULL; 2127 if (v == NULL) { 2128 d = PyEval_GetLocals(); 2129 if (d == NULL) { 2130 if (!PyErr_Occurred()) 2131 PyErr_SetString(PyExc_SystemError, 2132 "no locals!?"); 2133 } 2134 else 2135 Py_INCREF(d); 2136 } 2137 else { 2138 d = PyObject_GetAttrString(v, "__dict__"); 2139 if (d == NULL) { 2140 PyErr_SetString(PyExc_TypeError, 2141 "vars() argument must have __dict__ attribute"); 2142 return NULL; 2143 } 2144 } 2145 return d; 2146} 2147 2148static char vars_doc[] = 2149"vars([object]) -> dictionary\n\ 2150\n\ 2151Without arguments, equivalent to locals().\n\ 2152With an argument, equivalent to object.__dict__."; 2153 2154static int 2155abstract_issubclass(derived, cls, err, first) 2156 PyObject *derived; 2157 PyObject *cls; 2158 char *err; 2159 int first; 2160{ 2161 static PyObject *__bases__ = NULL; 2162 PyObject *bases; 2163 int i, n; 2164 int r = 0; 2165 2166 if (__bases__ == NULL) { 2167 __bases__ = PyString_FromString("__bases__"); 2168 if (__bases__ == NULL) 2169 return -1; 2170 } 2171 2172 if (first) { 2173 bases = PyObject_GetAttr(cls, __bases__); 2174 if (bases == NULL || !PyTuple_Check(bases)) { 2175 Py_XDECREF(bases); 2176 PyErr_SetString(PyExc_TypeError, err); 2177 return -1; 2178 } 2179 Py_DECREF(bases); 2180 } 2181 2182 if (derived == cls) 2183 return 1; 2184 2185 bases = PyObject_GetAttr(derived, __bases__); 2186 if (bases == NULL || !PyTuple_Check(bases)) { 2187 Py_XDECREF(bases); 2188 PyErr_SetString(PyExc_TypeError, err); 2189 return -1; 2190 } 2191 2192 n = PyTuple_GET_SIZE(bases); 2193 for (i = 0; i < n; i++) { 2194 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), 2195 cls, err, 0); 2196 if (r != 0) 2197 break; 2198 } 2199 2200 Py_DECREF(bases); 2201 2202 return r; 2203} 2204 2205static PyObject * 2206builtin_isinstance(self, args) 2207 PyObject *self; 2208 PyObject *args; 2209{ 2210 PyObject *inst; 2211 PyObject *cls; 2212 PyObject *icls; 2213 static PyObject *__class__ = NULL; 2214 int retval = 0; 2215 2216 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls)) 2217 return NULL; 2218 2219 if (PyClass_Check(cls)) { 2220 if (PyInstance_Check(inst)) { 2221 PyObject *inclass = 2222 (PyObject*)((PyInstanceObject*)inst)->in_class; 2223 retval = PyClass_IsSubclass(inclass, cls); 2224 } 2225 } 2226 else if (PyType_Check(cls)) { 2227 retval = ((PyObject *)(inst->ob_type) == cls); 2228 } 2229 else if (!PyInstance_Check(inst)) { 2230 if (__class__ == NULL) { 2231 __class__ = PyString_FromString("__class__"); 2232 if (__class__ == NULL) 2233 return NULL; 2234 } 2235 icls = PyObject_GetAttr(inst, __class__); 2236 if (icls != NULL) { 2237 retval = abstract_issubclass( 2238 icls, cls, 2239 "second argument must be a class", 2240 1); 2241 Py_DECREF(icls); 2242 if (retval < 0) 2243 return NULL; 2244 } 2245 else { 2246 PyErr_SetString(PyExc_TypeError, 2247 "second argument must be a class"); 2248 return NULL; 2249 } 2250 } 2251 else { 2252 PyErr_SetString(PyExc_TypeError, 2253 "second argument must be a class"); 2254 return NULL; 2255 } 2256 return PyInt_FromLong(retval); 2257} 2258 2259static char isinstance_doc[] = 2260"isinstance(object, class-or-type) -> Boolean\n\ 2261\n\ 2262Return whether an object is an instance of a class or of a subclass thereof.\n\ 2263With a type as second argument, return whether that is the object's type."; 2264 2265 2266static PyObject * 2267builtin_issubclass(self, args) 2268 PyObject *self; 2269 PyObject *args; 2270{ 2271 PyObject *derived; 2272 PyObject *cls; 2273 int retval; 2274 2275 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls)) 2276 return NULL; 2277 2278 if (!PyClass_Check(derived) || !PyClass_Check(cls)) { 2279 retval = abstract_issubclass( 2280 derived, cls, "arguments must be classes", 1); 2281 if (retval < 0) 2282 return NULL; 2283 } 2284 else { 2285 /* shortcut */ 2286 if (!(retval = (derived == cls))) 2287 retval = PyClass_IsSubclass(derived, cls); 2288 } 2289 2290 return PyInt_FromLong(retval); 2291} 2292 2293static char issubclass_doc[] = 2294"issubclass(C, B) -> Boolean\n\ 2295\n\ 2296Return whether class C is a subclass (i.e., a derived class) of class B."; 2297 2298 2299static PyMethodDef builtin_methods[] = { 2300 {"__import__", builtin___import__, 1, import_doc}, 2301 {"abs", builtin_abs, 1, abs_doc}, 2302 {"apply", builtin_apply, 1, apply_doc}, 2303 {"buffer", builtin_buffer, 1, buffer_doc}, 2304 {"callable", builtin_callable, 1, callable_doc}, 2305 {"chr", builtin_chr, 1, chr_doc}, 2306 {"cmp", builtin_cmp, 1, cmp_doc}, 2307 {"coerce", builtin_coerce, 1, coerce_doc}, 2308 {"compile", builtin_compile, 1, compile_doc}, 2309#ifndef WITHOUT_COMPLEX 2310 {"complex", builtin_complex, 1, complex_doc}, 2311#endif 2312 {"delattr", builtin_delattr, 1, delattr_doc}, 2313 {"dir", builtin_dir, 1, dir_doc}, 2314 {"divmod", builtin_divmod, 1, divmod_doc}, 2315 {"eval", builtin_eval, 1, eval_doc}, 2316 {"execfile", builtin_execfile, 1, execfile_doc}, 2317 {"filter", builtin_filter, 1, filter_doc}, 2318 {"float", builtin_float, 1, float_doc}, 2319 {"getattr", builtin_getattr, 1, getattr_doc}, 2320 {"globals", builtin_globals, 1, globals_doc}, 2321 {"hasattr", builtin_hasattr, 1, hasattr_doc}, 2322 {"hash", builtin_hash, 1, hash_doc}, 2323 {"hex", builtin_hex, 1, hex_doc}, 2324 {"id", builtin_id, 1, id_doc}, 2325 {"input", builtin_input, 1, input_doc}, 2326 {"intern", builtin_intern, 1, intern_doc}, 2327 {"int", builtin_int, 1, int_doc}, 2328 {"isinstance", builtin_isinstance, 1, isinstance_doc}, 2329 {"issubclass", builtin_issubclass, 1, issubclass_doc}, 2330 {"len", builtin_len, 1, len_doc}, 2331 {"list", builtin_list, 1, list_doc}, 2332 {"locals", builtin_locals, 1, locals_doc}, 2333 {"long", builtin_long, 1, long_doc}, 2334 {"map", builtin_map, 1, map_doc}, 2335 {"max", builtin_max, 1, max_doc}, 2336 {"min", builtin_min, 1, min_doc}, 2337 {"oct", builtin_oct, 1, oct_doc}, 2338 {"open", builtin_open, 1, open_doc}, 2339 {"ord", builtin_ord, 1, ord_doc}, 2340 {"pow", builtin_pow, 1, pow_doc}, 2341 {"range", builtin_range, 1, range_doc}, 2342 {"raw_input", builtin_raw_input, 1, raw_input_doc}, 2343 {"reduce", builtin_reduce, 1, reduce_doc}, 2344 {"reload", builtin_reload, 1, reload_doc}, 2345 {"repr", builtin_repr, 1, repr_doc}, 2346 {"round", builtin_round, 1, round_doc}, 2347 {"setattr", builtin_setattr, 1, setattr_doc}, 2348 {"slice", builtin_slice, 1, slice_doc}, 2349 {"str", builtin_str, 1, str_doc}, 2350 {"tuple", builtin_tuple, 1, tuple_doc}, 2351 {"type", builtin_type, 1, type_doc}, 2352 {"unicode", builtin_unicode, 1, unicode_doc}, 2353 {"unichr", builtin_unichr, 1, unichr_doc}, 2354 {"vars", builtin_vars, 1, vars_doc}, 2355 {"xrange", builtin_xrange, 1, xrange_doc}, 2356 {NULL, NULL}, 2357}; 2358 2359/* Predefined exceptions */ 2360 2361PyObject *PyExc_Exception; 2362PyObject *PyExc_StandardError; 2363PyObject *PyExc_ArithmeticError; 2364PyObject *PyExc_LookupError; 2365 2366PyObject *PyExc_AssertionError; 2367PyObject *PyExc_AttributeError; 2368PyObject *PyExc_EOFError; 2369PyObject *PyExc_FloatingPointError; 2370PyObject *PyExc_EnvironmentError; 2371PyObject *PyExc_IOError; 2372PyObject *PyExc_OSError; 2373PyObject *PyExc_ImportError; 2374PyObject *PyExc_IndexError; 2375PyObject *PyExc_KeyError; 2376PyObject *PyExc_KeyboardInterrupt; 2377PyObject *PyExc_MemoryError; 2378PyObject *PyExc_NameError; 2379PyObject *PyExc_OverflowError; 2380PyObject *PyExc_RuntimeError; 2381PyObject *PyExc_NotImplementedError; 2382PyObject *PyExc_SyntaxError; 2383PyObject *PyExc_SystemError; 2384PyObject *PyExc_SystemExit; 2385PyObject *PyExc_UnboundLocalError; 2386PyObject *PyExc_UnicodeError; 2387PyObject *PyExc_TypeError; 2388PyObject *PyExc_ValueError; 2389PyObject *PyExc_ZeroDivisionError; 2390#ifdef MS_WINDOWS 2391PyObject *PyExc_WindowsError; 2392#endif 2393 2394PyObject *PyExc_MemoryErrorInst; 2395 2396static struct 2397{ 2398 char* name; 2399 PyObject** exc; 2400 int leaf_exc; 2401} 2402bltin_exc[] = { 2403 {"Exception", &PyExc_Exception, 0}, 2404 {"StandardError", &PyExc_StandardError, 0}, 2405 {"ArithmeticError", &PyExc_ArithmeticError, 0}, 2406 {"LookupError", &PyExc_LookupError, 0}, 2407 {"AssertionError", &PyExc_AssertionError, 1}, 2408 {"AttributeError", &PyExc_AttributeError, 1}, 2409 {"EOFError", &PyExc_EOFError, 1}, 2410 {"FloatingPointError", &PyExc_FloatingPointError, 1}, 2411 {"EnvironmentError", &PyExc_EnvironmentError, 0}, 2412 {"IOError", &PyExc_IOError, 1}, 2413 {"OSError", &PyExc_OSError, 1}, 2414 {"ImportError", &PyExc_ImportError, 1}, 2415 {"IndexError", &PyExc_IndexError, 1}, 2416 {"KeyError", &PyExc_KeyError, 1}, 2417 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 1}, 2418 {"MemoryError", &PyExc_MemoryError, 1}, 2419 /* Note: NameError is not a leaf in exceptions.py, but unlike 2420 the other non-leafs NameError is meant to be raised directly 2421 at times -- the leaf_exc member really seems to mean something 2422 like "this is an abstract base class" when false. 2423 */ 2424 {"NameError", &PyExc_NameError, 1}, 2425 {"OverflowError", &PyExc_OverflowError, 1}, 2426 {"RuntimeError", &PyExc_RuntimeError, 1}, 2427 {"NotImplementedError",&PyExc_NotImplementedError,1}, 2428 {"SyntaxError", &PyExc_SyntaxError, 1}, 2429 {"SystemError", &PyExc_SystemError, 1}, 2430 {"SystemExit", &PyExc_SystemExit, 1}, 2431 {"UnboundLocalError", &PyExc_UnboundLocalError, 1}, 2432 {"UnicodeError", &PyExc_UnicodeError, 1}, 2433 {"TypeError", &PyExc_TypeError, 1}, 2434 {"ValueError", &PyExc_ValueError, 1}, 2435#ifdef MS_WINDOWS 2436 {"WindowsError", &PyExc_WindowsError, 1}, 2437#endif 2438 {"ZeroDivisionError", &PyExc_ZeroDivisionError, 1}, 2439 {NULL, NULL} 2440}; 2441 2442 2443/* Import exceptions module to extract class exceptions. On success, 2444 * return 1. On failure return 0 which signals _PyBuiltin_Init_2 to 2445 * issue a fatal error. 2446 */ 2447static int 2448init_class_exc(dict) 2449 PyObject *dict; 2450{ 2451 int i; 2452 PyObject *m = PyImport_ImportModule("exceptions"); 2453 PyObject *args = NULL; 2454 PyObject *d = NULL; 2455 2456 /* make sure we got the module and its dictionary */ 2457 if (m == NULL || 2458 (d = PyModule_GetDict(m)) == NULL) 2459 { 2460 PySys_WriteStderr("'import exceptions' failed\n"); 2461 goto finally; 2462 } 2463 for (i = 0; bltin_exc[i].name; i++) { 2464 /* dig the exception out of the module */ 2465 PyObject *exc = PyDict_GetItemString(d, bltin_exc[i].name); 2466 if (!exc) { 2467 PySys_WriteStderr( 2468 "Built-in exception class not found: %s. Library mismatch?\n", 2469 bltin_exc[i].name); 2470 goto finally; 2471 } 2472 /* free the old-style exception string object */ 2473 Py_XDECREF(*bltin_exc[i].exc); 2474 2475 /* squirrel away a pointer to the exception */ 2476 Py_INCREF(exc); 2477 *bltin_exc[i].exc = exc; 2478 2479 /* and insert the name in the __builtin__ module */ 2480 if (PyDict_SetItemString(dict, bltin_exc[i].name, exc)) { 2481 PySys_WriteStderr( 2482 "Cannot insert exception into __builtin__: %s\n", 2483 bltin_exc[i].name); 2484 goto finally; 2485 } 2486 } 2487 2488 /* we need one pre-allocated instance */ 2489 args = Py_BuildValue("()"); 2490 if (!args || 2491 !(PyExc_MemoryErrorInst = 2492 PyEval_CallObject(PyExc_MemoryError, args))) 2493 { 2494 PySys_WriteStderr("Cannot pre-allocate MemoryError instance\n"); 2495 goto finally; 2496 } 2497 Py_DECREF(args); 2498 2499 /* we're done with the exceptions module */ 2500 Py_DECREF(m); 2501 return 1; 2502 2503 finally: 2504 Py_XDECREF(m); 2505 Py_XDECREF(args); 2506 PyErr_Clear(); 2507 return 0; 2508} 2509 2510 2511static void 2512fini_instances() 2513{ 2514 Py_XDECREF(PyExc_MemoryErrorInst); 2515 PyExc_MemoryErrorInst = NULL; 2516} 2517 2518 2519static void 2520finierrors() 2521{ 2522 int i; 2523 for (i = 0; bltin_exc[i].name; i++) { 2524 PyObject *exc = *bltin_exc[i].exc; 2525 Py_XDECREF(exc); 2526 *bltin_exc[i].exc = NULL; 2527 } 2528} 2529 2530static char builtin_doc[] = 2531"Built-in functions, exceptions, and other objects.\n\ 2532\n\ 2533Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."; 2534 2535PyObject * 2536_PyBuiltin_Init_1() 2537{ 2538 PyObject *mod, *dict; 2539 mod = Py_InitModule4("__builtin__", builtin_methods, 2540 builtin_doc, (PyObject *)NULL, 2541 PYTHON_API_VERSION); 2542 if (mod == NULL) 2543 return NULL; 2544 dict = PyModule_GetDict(mod); 2545 if (PyDict_SetItemString(dict, "None", Py_None) < 0) 2546 return NULL; 2547 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0) 2548 return NULL; 2549 if (PyDict_SetItemString(dict, "__debug__", 2550 PyInt_FromLong(Py_OptimizeFlag == 0)) < 0) 2551 return NULL; 2552 2553 return mod; 2554} 2555 2556void 2557_PyBuiltin_Init_2(dict) 2558 PyObject *dict; 2559{ 2560 if (!init_class_exc(dict)) 2561 /* class based exceptions could not be initialized. */ 2562 Py_FatalError("Standard exceptions could not be initialized."); 2563} 2564 2565 2566void 2567_PyBuiltin_Fini_1() 2568{ 2569 fini_instances(); 2570} 2571 2572 2573void 2574_PyBuiltin_Fini_2() 2575{ 2576 finierrors(); 2577} 2578 2579 2580/* Helper for filter(): filter a tuple through a function */ 2581 2582static PyObject * 2583filtertuple(func, tuple) 2584 PyObject *func; 2585 PyObject *tuple; 2586{ 2587 PyObject *result; 2588 register int i, j; 2589 int len = PyTuple_Size(tuple); 2590 2591 if (len == 0) { 2592 Py_INCREF(tuple); 2593 return tuple; 2594 } 2595 2596 if ((result = PyTuple_New(len)) == NULL) 2597 return NULL; 2598 2599 for (i = j = 0; i < len; ++i) { 2600 PyObject *item, *good; 2601 int ok; 2602 2603 if ((item = PyTuple_GetItem(tuple, i)) == NULL) 2604 goto Fail_1; 2605 if (func == Py_None) { 2606 Py_INCREF(item); 2607 good = item; 2608 } 2609 else { 2610 PyObject *arg = Py_BuildValue("(O)", item); 2611 if (arg == NULL) 2612 goto Fail_1; 2613 good = PyEval_CallObject(func, arg); 2614 Py_DECREF(arg); 2615 if (good == NULL) 2616 goto Fail_1; 2617 } 2618 ok = PyObject_IsTrue(good); 2619 Py_DECREF(good); 2620 if (ok) { 2621 Py_INCREF(item); 2622 if (PyTuple_SetItem(result, j++, item) < 0) 2623 goto Fail_1; 2624 } 2625 } 2626 2627 if (_PyTuple_Resize(&result, j, 0) < 0) 2628 return NULL; 2629 2630 return result; 2631 2632Fail_1: 2633 Py_DECREF(result); 2634 return NULL; 2635} 2636 2637 2638/* Helper for filter(): filter a string through a function */ 2639 2640static PyObject * 2641filterstring(func, strobj) 2642 PyObject *func; 2643 PyObject *strobj; 2644{ 2645 PyObject *result; 2646 register int i, j; 2647 int len = PyString_Size(strobj); 2648 2649 if (func == Py_None) { 2650 /* No character is ever false -- share input string */ 2651 Py_INCREF(strobj); 2652 return strobj; 2653 } 2654 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL) 2655 return NULL; 2656 2657 for (i = j = 0; i < len; ++i) { 2658 PyObject *item, *arg, *good; 2659 int ok; 2660 2661 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i); 2662 if (item == NULL) 2663 goto Fail_1; 2664 arg = Py_BuildValue("(O)", item); 2665 Py_DECREF(item); 2666 if (arg == NULL) 2667 goto Fail_1; 2668 good = PyEval_CallObject(func, arg); 2669 Py_DECREF(arg); 2670 if (good == NULL) 2671 goto Fail_1; 2672 ok = PyObject_IsTrue(good); 2673 Py_DECREF(good); 2674 if (ok) 2675 PyString_AS_STRING((PyStringObject *)result)[j++] = 2676 PyString_AS_STRING((PyStringObject *)item)[0]; 2677 } 2678 2679 if (j < len && _PyString_Resize(&result, j) < 0) 2680 return NULL; 2681 2682 return result; 2683 2684Fail_1: 2685 Py_DECREF(result); 2686 return NULL; 2687} 2688