home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Python / bltinmodule.c < prev    next >
C/C++ Source or Header  |  2000-12-21  |  63KB  |  2,695 lines

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