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