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