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