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