Updated for 2.1a3
[python/dscho.git] / Python / bltinmodule.c
blobe5db11ec7840e8c1c0614ef68c21f25b741bd4e7
2 /* Built-in functions */
4 #include "Python.h"
6 #include "node.h"
7 #include "compile.h"
8 #include "eval.h"
10 #include <ctype.h>
12 #ifdef HAVE_UNISTD_H
13 #include <unistd.h>
14 #endif
16 /* Forward */
17 static PyObject *filterstring(PyObject *, PyObject *);
18 static PyObject *filtertuple (PyObject *, PyObject *);
20 static PyObject *
21 builtin___import__(PyObject *self, PyObject *args)
23 char *name;
24 PyObject *globals = NULL;
25 PyObject *locals = NULL;
26 PyObject *fromlist = NULL;
28 if (!PyArg_ParseTuple(args, "s|OOO:__import__",
29 &name, &globals, &locals, &fromlist))
30 return NULL;
31 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
34 static char import_doc[] =
35 "__import__(name, globals, locals, fromlist) -> module\n\
36 \n\
37 Import a module. The globals are only used to determine the context;\n\
38 they are not modified. The locals are currently unused. The fromlist\n\
39 should be a list of names to emulate ``from name import ...'', or an\n\
40 empty list to emulate ``import name''.\n\
41 When importing a module from a package, note that __import__('A.B', ...)\n\
42 returns package A when fromlist is empty, but its submodule B when\n\
43 fromlist is not empty.";
46 static PyObject *
47 builtin_abs(PyObject *self, PyObject *args)
49 PyObject *v;
51 if (!PyArg_ParseTuple(args, "O:abs", &v))
52 return NULL;
53 return PyNumber_Absolute(v);
56 static char abs_doc[] =
57 "abs(number) -> number\n\
58 \n\
59 Return the absolute value of the argument.";
62 static PyObject *
63 builtin_apply(PyObject *self, PyObject *args)
65 PyObject *func, *alist = NULL, *kwdict = NULL;
66 PyObject *t = NULL, *retval = NULL;
68 if (!PyArg_ParseTuple(args, "O|OO:apply", &func, &alist, &kwdict))
69 return NULL;
70 if (alist != NULL) {
71 if (!PyTuple_Check(alist)) {
72 if (!PySequence_Check(alist)) {
73 PyErr_Format(PyExc_TypeError,
74 "apply() arg 2 expect sequence, found %s",
75 alist->ob_type->tp_name);
76 return NULL;
78 t = PySequence_Tuple(alist);
79 if (t == NULL)
80 return NULL;
81 alist = t;
84 if (kwdict != NULL && !PyDict_Check(kwdict)) {
85 PyErr_Format(PyExc_TypeError,
86 "apply() arg 3 expected dictionary, found %s",
87 kwdict->ob_type->tp_name);
88 goto finally;
90 retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
91 finally:
92 Py_XDECREF(t);
93 return retval;
96 static char apply_doc[] =
97 "apply(object[, args[, kwargs]]) -> value\n\
98 \n\
99 Call a callable object with positional arguments taken from the tuple args,\n\
100 and keyword arguments taken from the optional dictionary kwargs.\n\
101 Note that classes are callable, as are instances with a __call__() method.";
104 static PyObject *
105 builtin_buffer(PyObject *self, PyObject *args)
107 PyObject *ob;
108 int offset = 0;
109 int size = Py_END_OF_BUFFER;
111 if ( !PyArg_ParseTuple(args, "O|ii:buffer", &ob, &offset, &size) )
112 return NULL;
113 return PyBuffer_FromObject(ob, offset, size);
116 static char buffer_doc[] =
117 "buffer(object [, offset[, size]]) -> object\n\
119 Create a new buffer object which references the given object.\n\
120 The buffer will reference a slice of the target object from the\n\
121 start of the object (or at the specified offset). The slice will\n\
122 extend to the end of the target object (or with the specified size).";
125 static PyObject *
126 builtin_unicode(PyObject *self, PyObject *args)
128 PyObject *v;
129 char *encoding = NULL;
130 char *errors = NULL;
132 if ( !PyArg_ParseTuple(args, "O|ss:unicode", &v, &encoding, &errors) )
133 return NULL;
134 return PyUnicode_FromEncodedObject(v, encoding, errors);
137 static char unicode_doc[] =
138 "unicode(string [, encoding[, errors]]) -> object\n\
140 Create a new Unicode object from the given encoded string.\n\
141 encoding defaults to the current default string encoding and \n\
142 errors, defining the error handling, to 'strict'.";
145 static PyObject *
146 builtin_callable(PyObject *self, PyObject *args)
148 PyObject *v;
150 if (!PyArg_ParseTuple(args, "O:callable", &v))
151 return NULL;
152 return PyInt_FromLong((long)PyCallable_Check(v));
155 static char callable_doc[] =
156 "callable(object) -> Boolean\n\
158 Return whether the object is callable (i.e., some kind of function).\n\
159 Note that classes are callable, as are instances with a __call__() method.";
162 static PyObject *
163 builtin_filter(PyObject *self, PyObject *args)
165 PyObject *func, *seq, *result;
166 PySequenceMethods *sqf;
167 int len;
168 register int i, j;
170 if (!PyArg_ParseTuple(args, "OO:filter", &func, &seq))
171 return NULL;
173 if (PyString_Check(seq)) {
174 PyObject *r = filterstring(func, seq);
175 return r;
178 if (PyTuple_Check(seq)) {
179 PyObject *r = filtertuple(func, seq);
180 return r;
183 sqf = seq->ob_type->tp_as_sequence;
184 if (sqf == NULL || sqf->sq_length == NULL || sqf->sq_item == NULL) {
185 PyErr_SetString(PyExc_TypeError,
186 "filter() arg 2 must be a sequence");
187 goto Fail_2;
190 if ((len = (*sqf->sq_length)(seq)) < 0)
191 goto Fail_2;
193 if (PyList_Check(seq) && seq->ob_refcnt == 1) {
194 Py_INCREF(seq);
195 result = seq;
197 else {
198 if ((result = PyList_New(len)) == NULL)
199 goto Fail_2;
202 for (i = j = 0; ; ++i) {
203 PyObject *item, *good;
204 int ok;
206 if ((item = (*sqf->sq_item)(seq, i)) == NULL) {
207 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
208 PyErr_Clear();
209 break;
211 goto Fail_1;
214 if (func == Py_None) {
215 good = item;
216 Py_INCREF(good);
218 else {
219 PyObject *arg = Py_BuildValue("(O)", item);
220 if (arg == NULL)
221 goto Fail_1;
222 good = PyEval_CallObject(func, arg);
223 Py_DECREF(arg);
224 if (good == NULL) {
225 Py_DECREF(item);
226 goto Fail_1;
229 ok = PyObject_IsTrue(good);
230 Py_DECREF(good);
231 if (ok) {
232 if (j < len) {
233 if (PyList_SetItem(result, j++, item) < 0)
234 goto Fail_1;
236 else {
237 int status = PyList_Append(result, item);
238 j++;
239 Py_DECREF(item);
240 if (status < 0)
241 goto Fail_1;
243 } else {
244 Py_DECREF(item);
249 if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
250 goto Fail_1;
252 return result;
254 Fail_1:
255 Py_DECREF(result);
256 Fail_2:
257 return NULL;
260 static char filter_doc[] =
261 "filter(function, sequence) -> list\n\
263 Return a list containing those items of sequence for which function(item)\n\
264 is true. If function is None, return a list of items that are true.";
267 static PyObject *
268 builtin_chr(PyObject *self, PyObject *args)
270 long x;
271 char s[1];
273 if (!PyArg_ParseTuple(args, "l:chr", &x))
274 return NULL;
275 if (x < 0 || x >= 256) {
276 PyErr_SetString(PyExc_ValueError,
277 "chr() arg not in range(256)");
278 return NULL;
280 s[0] = (char)x;
281 return PyString_FromStringAndSize(s, 1);
284 static char chr_doc[] =
285 "chr(i) -> character\n\
287 Return a string of one character with ordinal i; 0 <= i < 256.";
290 static PyObject *
291 builtin_unichr(PyObject *self, PyObject *args)
293 long x;
294 Py_UNICODE s[1];
296 if (!PyArg_ParseTuple(args, "l:unichr", &x))
297 return NULL;
298 if (x < 0 || x >= 65536) {
299 PyErr_SetString(PyExc_ValueError,
300 "unichr() arg not in range(65536)");
301 return NULL;
303 s[0] = (Py_UNICODE)x;
304 return PyUnicode_FromUnicode(s, 1);
307 static char unichr_doc[] =
308 "unichr(i) -> Unicode character\n\
310 Return a Unicode string of one character with ordinal i; 0 <= i < 65536.";
313 static PyObject *
314 builtin_cmp(PyObject *self, PyObject *args)
316 PyObject *a, *b;
317 int c;
319 if (!PyArg_ParseTuple(args, "OO:cmp", &a, &b))
320 return NULL;
321 if (PyObject_Cmp(a, b, &c) < 0)
322 return NULL;
323 return PyInt_FromLong((long)c);
326 static char cmp_doc[] =
327 "cmp(x, y) -> integer\n\
329 Return negative if x<y, zero if x==y, positive if x>y.";
332 static PyObject *
333 builtin_coerce(PyObject *self, PyObject *args)
335 PyObject *v, *w;
336 PyObject *res;
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;
348 static char coerce_doc[] =
349 "coerce(x, y) -> None or (x1, y1)\n\
351 When x and y can be coerced to values of the same type, return a tuple\n\
352 containing the coerced values. When they can't be coerced, return None.";
355 static PyObject *
356 builtin_compile(PyObject *self, PyObject *args)
358 char *str;
359 char *filename;
360 char *startstr;
361 int start;
363 if (!PyArg_ParseTuple(args, "sss:compile", &str, &filename, &startstr))
364 return NULL;
365 if (strcmp(startstr, "exec") == 0)
366 start = Py_file_input;
367 else if (strcmp(startstr, "eval") == 0)
368 start = Py_eval_input;
369 else if (strcmp(startstr, "single") == 0)
370 start = Py_single_input;
371 else {
372 PyErr_SetString(PyExc_ValueError,
373 "compile() arg 3 must be 'exec' or 'eval' or 'single'");
374 return NULL;
376 return Py_CompileString(str, filename, start);
379 static char compile_doc[] =
380 "compile(source, filename, mode) -> code object\n\
382 Compile the source string (a Python module, statement or expression)\n\
383 into a code object that can be executed by the exec statement or eval().\n\
384 The filename will be used for run-time error messages.\n\
385 The mode must be 'exec' to compile a module, 'single' to compile a\n\
386 single (interactive) statement, or 'eval' to compile an expression.";
389 #ifndef WITHOUT_COMPLEX
391 static PyObject *
392 complex_from_string(PyObject *v)
394 extern double strtod(const char *, char **);
395 const char *s, *start;
396 char *end;
397 double x=0.0, y=0.0, z;
398 int got_re=0, got_im=0, done=0;
399 int digit_or_dot;
400 int sw_error=0;
401 int sign;
402 char buffer[256]; /* For errors */
403 char s_buffer[256];
404 int len;
406 if (PyString_Check(v)) {
407 s = PyString_AS_STRING(v);
408 len = PyString_GET_SIZE(v);
410 else if (PyUnicode_Check(v)) {
411 if (PyUnicode_GET_SIZE(v) >= sizeof(s_buffer)) {
412 PyErr_SetString(PyExc_ValueError,
413 "complex() literal too large to convert");
414 return NULL;
416 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
417 PyUnicode_GET_SIZE(v),
418 s_buffer,
419 NULL))
420 return NULL;
421 s = s_buffer;
422 len = (int)strlen(s);
424 else if (PyObject_AsCharBuffer(v, &s, &len)) {
425 PyErr_SetString(PyExc_TypeError,
426 "complex() arg is not a string");
427 return NULL;
430 /* position on first nonblank */
431 start = s;
432 while (*s && isspace(Py_CHARMASK(*s)))
433 s++;
434 if (s[0] == '\0') {
435 PyErr_SetString(PyExc_ValueError,
436 "complex() arg is an empty string");
437 return NULL;
440 z = -1.0;
441 sign = 1;
442 do {
444 switch (*s) {
446 case '\0':
447 if (s-start != len) {
448 PyErr_SetString(
449 PyExc_ValueError,
450 "complex() arg contains a null byte");
451 return NULL;
453 if(!done) sw_error=1;
454 break;
456 case '-':
457 sign = -1;
458 /* Fallthrough */
459 case '+':
460 if (done) sw_error=1;
461 s++;
462 if ( *s=='\0'||*s=='+'||*s=='-' ||
463 isspace(Py_CHARMASK(*s)) ) sw_error=1;
464 break;
466 case 'J':
467 case 'j':
468 if (got_im || done) {
469 sw_error = 1;
470 break;
472 if (z<0.0) {
473 y=sign;
475 else{
476 y=sign*z;
478 got_im=1;
479 s++;
480 if (*s!='+' && *s!='-' )
481 done=1;
482 break;
484 default:
485 if (isspace(Py_CHARMASK(*s))) {
486 while (*s && isspace(Py_CHARMASK(*s)))
487 s++;
488 if (s[0] != '\0')
489 sw_error=1;
490 else
491 done = 1;
492 break;
494 digit_or_dot =
495 (*s=='.' || isdigit(Py_CHARMASK(*s)));
496 if (done||!digit_or_dot) {
497 sw_error=1;
498 break;
500 errno = 0;
501 PyFPE_START_PROTECT("strtod", return 0)
502 z = strtod(s, &end) ;
503 PyFPE_END_PROTECT(z)
504 if (errno != 0) {
505 sprintf(buffer,
506 "float() out of range: %.150s", s);
507 PyErr_SetString(
508 PyExc_ValueError,
509 buffer);
510 return NULL;
512 s=end;
513 if (*s=='J' || *s=='j') {
515 break;
517 if (got_re) {
518 sw_error=1;
519 break;
522 /* accept a real part */
523 x=sign*z;
524 got_re=1;
525 if (got_im) done=1;
526 z = -1.0;
527 sign = 1;
528 break;
530 } /* end of switch */
532 } while (*s!='\0' && !sw_error);
534 if (sw_error) {
535 PyErr_SetString(PyExc_ValueError,
536 "complex() arg is a malformed string");
537 return NULL;
540 return PyComplex_FromDoubles(x,y);
543 static PyObject *
544 builtin_complex(PyObject *self, PyObject *args)
546 PyObject *r, *i, *tmp;
547 PyNumberMethods *nbr, *nbi = NULL;
548 Py_complex cr, ci;
549 int own_r = 0;
551 i = NULL;
552 if (!PyArg_ParseTuple(args, "O|O:complex", &r, &i))
553 return NULL;
554 if (PyString_Check(r) || PyUnicode_Check(r))
555 return complex_from_string(r);
556 if ((nbr = r->ob_type->tp_as_number) == NULL ||
557 nbr->nb_float == NULL ||
558 (i != NULL &&
559 ((nbi = i->ob_type->tp_as_number) == NULL ||
560 nbi->nb_float == NULL))) {
561 PyErr_SetString(PyExc_TypeError,
562 "complex() arg can't be converted to complex");
563 return NULL;
565 /* XXX Hack to support classes with __complex__ method */
566 if (PyInstance_Check(r)) {
567 static PyObject *complexstr;
568 PyObject *f;
569 if (complexstr == NULL) {
570 complexstr = PyString_InternFromString("__complex__");
571 if (complexstr == NULL)
572 return NULL;
574 f = PyObject_GetAttr(r, complexstr);
575 if (f == NULL)
576 PyErr_Clear();
577 else {
578 PyObject *args = Py_BuildValue("()");
579 if (args == NULL)
580 return NULL;
581 r = PyEval_CallObject(f, args);
582 Py_DECREF(args);
583 Py_DECREF(f);
584 if (r == NULL)
585 return NULL;
586 own_r = 1;
589 if (PyComplex_Check(r)) {
590 cr = ((PyComplexObject*)r)->cval;
591 if (own_r) {
592 Py_DECREF(r);
595 else {
596 tmp = PyNumber_Float(r);
597 if (own_r) {
598 Py_DECREF(r);
600 if (tmp == NULL)
601 return NULL;
602 if (!PyFloat_Check(tmp)) {
603 PyErr_SetString(PyExc_TypeError,
604 "float(r) didn't return a float");
605 Py_DECREF(tmp);
606 return NULL;
608 cr.real = PyFloat_AsDouble(tmp);
609 Py_DECREF(tmp);
610 cr.imag = 0.0;
612 if (i == NULL) {
613 ci.real = 0.0;
614 ci.imag = 0.0;
616 else if (PyComplex_Check(i))
617 ci = ((PyComplexObject*)i)->cval;
618 else {
619 tmp = (*nbi->nb_float)(i);
620 if (tmp == NULL)
621 return NULL;
622 ci.real = PyFloat_AsDouble(tmp);
623 Py_DECREF(tmp);
624 ci.imag = 0.;
626 cr.real -= ci.imag;
627 cr.imag += ci.real;
628 return PyComplex_FromCComplex(cr);
631 static char complex_doc[] =
632 "complex(real[, imag]) -> complex number\n\
634 Create a complex number from a real part and an optional imaginary part.\n\
635 This is equivalent to (real + imag*1j) where imag defaults to 0.";
638 #endif
640 static PyObject *
641 builtin_dir(PyObject *self, PyObject *args)
643 static char *attrlist[] = {"__members__", "__methods__", NULL};
644 PyObject *v = NULL, *l = NULL, *m = NULL;
645 PyObject *d, *x;
646 int i;
647 char **s;
649 if (!PyArg_ParseTuple(args, "|O:dir", &v))
650 return NULL;
651 if (v == NULL) {
652 x = PyEval_GetLocals();
653 if (x == NULL)
654 goto error;
655 l = PyMapping_Keys(x);
656 if (l == NULL)
657 goto error;
659 else {
660 d = PyObject_GetAttrString(v, "__dict__");
661 if (d == NULL)
662 PyErr_Clear();
663 else {
664 l = PyMapping_Keys(d);
665 if (l == NULL)
666 PyErr_Clear();
667 Py_DECREF(d);
669 if (l == NULL) {
670 l = PyList_New(0);
671 if (l == NULL)
672 goto error;
674 for (s = attrlist; *s != NULL; s++) {
675 m = PyObject_GetAttrString(v, *s);
676 if (m == NULL) {
677 PyErr_Clear();
678 continue;
680 for (i = 0; ; i++) {
681 x = PySequence_GetItem(m, i);
682 if (x == NULL) {
683 PyErr_Clear();
684 break;
686 if (PyList_Append(l, x) != 0) {
687 Py_DECREF(x);
688 Py_DECREF(m);
689 goto error;
691 Py_DECREF(x);
693 Py_DECREF(m);
696 if (PyList_Sort(l) != 0)
697 goto error;
698 return l;
699 error:
700 Py_XDECREF(l);
701 return NULL;
704 static char dir_doc[] =
705 "dir([object]) -> list of strings\n\
707 Return an alphabetized list of names comprising (some of) the attributes\n\
708 of the given object. Without an argument, the names in the current scope\n\
709 are listed. With an instance argument, only the instance attributes are\n\
710 returned. With a class argument, attributes of the base class are not\n\
711 returned. For other types or arguments, this may list members or methods.";
714 static PyObject *
715 builtin_divmod(PyObject *self, PyObject *args)
717 PyObject *v, *w;
719 if (!PyArg_ParseTuple(args, "OO:divmod", &v, &w))
720 return NULL;
721 return PyNumber_Divmod(v, w);
724 static char divmod_doc[] =
725 "divmod(x, y) -> (div, mod)\n\
727 Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.";
730 static PyObject *
731 builtin_eval(PyObject *self, PyObject *args)
733 PyObject *cmd;
734 PyObject *globals = Py_None, *locals = Py_None;
735 char *str;
737 if (!PyArg_ParseTuple(args, "O|O!O!:eval",
738 &cmd,
739 &PyDict_Type, &globals,
740 &PyDict_Type, &locals))
741 return NULL;
742 if (globals == Py_None) {
743 globals = PyEval_GetGlobals();
744 if (locals == Py_None)
745 locals = PyEval_GetLocals();
747 else if (locals == Py_None)
748 locals = globals;
749 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
750 if (PyDict_SetItemString(globals, "__builtins__",
751 PyEval_GetBuiltins()) != 0)
752 return NULL;
754 if (PyCode_Check(cmd))
755 return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
756 if (!PyString_Check(cmd) &&
757 !PyUnicode_Check(cmd)) {
758 PyErr_SetString(PyExc_TypeError,
759 "eval() arg 1 must be a string or code object");
760 return NULL;
762 if (PyString_AsStringAndSize(cmd, &str, NULL))
763 return NULL;
764 while (*str == ' ' || *str == '\t')
765 str++;
766 return PyRun_String(str, Py_eval_input, globals, locals);
769 static char eval_doc[] =
770 "eval(source[, globals[, locals]]) -> value\n\
772 Evaluate the source in the context of globals and locals.\n\
773 The source may be a string representing a Python expression\n\
774 or a code object as returned by compile().\n\
775 The globals and locals are dictionaries, defaulting to the current\n\
776 globals and locals. If only globals is given, locals defaults to it.";
779 static PyObject *
780 builtin_execfile(PyObject *self, PyObject *args)
782 char *filename;
783 PyObject *globals = Py_None, *locals = Py_None;
784 PyObject *res;
785 FILE* fp;
787 if (!PyArg_ParseTuple(args, "s|O!O!:execfile",
788 &filename,
789 &PyDict_Type, &globals,
790 &PyDict_Type, &locals))
791 return NULL;
792 if (globals == Py_None) {
793 globals = PyEval_GetGlobals();
794 if (locals == Py_None)
795 locals = PyEval_GetLocals();
797 else if (locals == Py_None)
798 locals = globals;
799 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
800 if (PyDict_SetItemString(globals, "__builtins__",
801 PyEval_GetBuiltins()) != 0)
802 return NULL;
804 Py_BEGIN_ALLOW_THREADS
805 fp = fopen(filename, "r");
806 Py_END_ALLOW_THREADS
807 if (fp == NULL) {
808 PyErr_SetFromErrno(PyExc_IOError);
809 return NULL;
811 res = PyRun_FileEx(fp, filename, Py_file_input, globals, locals, 1);
812 return res;
815 static char execfile_doc[] =
816 "execfile(filename[, globals[, locals]])\n\
818 Read and execute a Python script from a file.\n\
819 The globals and locals are dictionaries, defaulting to the current\n\
820 globals and locals. If only globals is given, locals defaults to it.";
823 static PyObject *
824 builtin_getattr(PyObject *self, PyObject *args)
826 PyObject *v, *result, *dflt = NULL;
827 PyObject *name;
829 if (!PyArg_ParseTuple(args, "OO|O:getattr", &v, &name, &dflt))
830 return NULL;
831 result = PyObject_GetAttr(v, name);
832 if (result == NULL && dflt != NULL) {
833 PyErr_Clear();
834 Py_INCREF(dflt);
835 result = dflt;
837 return result;
840 static char getattr_doc[] =
841 "getattr(object, name[, default]) -> value\n\
843 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
844 When a default argument is given, it is returned when the attribute doesn't\n\
845 exist; without it, an exception is raised in that case.";
848 static PyObject *
849 builtin_globals(PyObject *self, PyObject *args)
851 PyObject *d;
853 if (!PyArg_ParseTuple(args, ":globals"))
854 return NULL;
855 d = PyEval_GetGlobals();
856 Py_INCREF(d);
857 return d;
860 static char globals_doc[] =
861 "globals() -> dictionary\n\
863 Return the dictionary containing the current scope's global variables.";
866 static PyObject *
867 builtin_hasattr(PyObject *self, PyObject *args)
869 PyObject *v;
870 PyObject *name;
872 if (!PyArg_ParseTuple(args, "OO:hasattr", &v, &name))
873 return NULL;
874 v = PyObject_GetAttr(v, name);
875 if (v == NULL) {
876 PyErr_Clear();
877 Py_INCREF(Py_False);
878 return Py_False;
880 Py_DECREF(v);
881 Py_INCREF(Py_True);
882 return Py_True;
885 static char hasattr_doc[] =
886 "hasattr(object, name) -> Boolean\n\
888 Return whether the object has an attribute with the given name.\n\
889 (This is done by calling getattr(object, name) and catching exceptions.)";
892 static PyObject *
893 builtin_id(PyObject *self, PyObject *args)
895 PyObject *v;
897 if (!PyArg_ParseTuple(args, "O:id", &v))
898 return NULL;
899 return PyLong_FromVoidPtr(v);
902 static char id_doc[] =
903 "id(object) -> integer\n\
905 Return the identity of an object. This is guaranteed to be unique among\n\
906 simultaneously existing objects. (Hint: it's the object's memory address.)";
909 static PyObject *
910 builtin_map(PyObject *self, PyObject *args)
912 typedef struct {
913 PyObject *seq;
914 PySequenceMethods *sqf;
915 int len;
916 } sequence;
918 PyObject *func, *result;
919 sequence *seqs = NULL, *sqp;
920 int n, len;
921 register int i, j;
923 n = PyTuple_Size(args);
924 if (n < 2) {
925 PyErr_SetString(PyExc_TypeError,
926 "map() requires at least two args");
927 return NULL;
930 func = PyTuple_GetItem(args, 0);
931 n--;
933 if (func == Py_None && n == 1) {
934 /* map(None, S) is the same as list(S). */
935 return PySequence_List(PyTuple_GetItem(args, 1));
938 if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
939 PyErr_NoMemory();
940 goto Fail_2;
943 for (len = 0, i = 0, sqp = seqs; i < n; ++i, ++sqp) {
944 int curlen;
945 PySequenceMethods *sqf;
947 if ((sqp->seq = PyTuple_GetItem(args, i + 1)) == NULL)
948 goto Fail_2;
950 sqp->sqf = sqf = sqp->seq->ob_type->tp_as_sequence;
951 if (sqf == NULL ||
952 sqf->sq_length == NULL ||
953 sqf->sq_item == NULL)
955 static char errmsg[] =
956 "argument %d to map() must be a sequence object";
957 char errbuf[sizeof(errmsg) + 25];
959 sprintf(errbuf, errmsg, i+2);
960 PyErr_SetString(PyExc_TypeError, errbuf);
961 goto Fail_2;
964 if ((curlen = sqp->len = (*sqp->sqf->sq_length)(sqp->seq)) < 0)
965 goto Fail_2;
967 if (curlen > len)
968 len = curlen;
971 if ((result = (PyObject *) PyList_New(len)) == NULL)
972 goto Fail_2;
974 for (i = 0; ; ++i) {
975 PyObject *alist, *item=NULL, *value;
976 int any = 0;
978 if (func == Py_None && n == 1)
979 alist = NULL;
980 else {
981 if ((alist = PyTuple_New(n)) == NULL)
982 goto Fail_1;
985 for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
986 if (sqp->len < 0) {
987 Py_INCREF(Py_None);
988 item = Py_None;
990 else {
991 item = (*sqp->sqf->sq_item)(sqp->seq, i);
992 if (item == NULL) {
993 if (PyErr_ExceptionMatches(
994 PyExc_IndexError))
996 PyErr_Clear();
997 Py_INCREF(Py_None);
998 item = Py_None;
999 sqp->len = -1;
1001 else {
1002 goto Fail_0;
1005 else
1006 any = 1;
1009 if (!alist)
1010 break;
1011 if (PyTuple_SetItem(alist, j, item) < 0) {
1012 Py_DECREF(item);
1013 goto Fail_0;
1015 continue;
1017 Fail_0:
1018 Py_XDECREF(alist);
1019 goto Fail_1;
1022 if (!alist)
1023 alist = item;
1025 if (!any) {
1026 Py_DECREF(alist);
1027 break;
1030 if (func == Py_None)
1031 value = alist;
1032 else {
1033 value = PyEval_CallObject(func, alist);
1034 Py_DECREF(alist);
1035 if (value == NULL)
1036 goto Fail_1;
1038 if (i >= len) {
1039 int status = PyList_Append(result, value);
1040 Py_DECREF(value);
1041 if (status < 0)
1042 goto Fail_1;
1044 else {
1045 if (PyList_SetItem(result, i, value) < 0)
1046 goto Fail_1;
1050 if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
1051 goto Fail_1;
1053 PyMem_DEL(seqs);
1054 return result;
1056 Fail_1:
1057 Py_DECREF(result);
1058 Fail_2:
1059 if (seqs) PyMem_DEL(seqs);
1060 return NULL;
1063 static char map_doc[] =
1064 "map(function, sequence[, sequence, ...]) -> list\n\
1066 Return a list of the results of applying the function to the items of\n\
1067 the argument sequence(s). If more than one sequence is given, the\n\
1068 function is called with an argument list consisting of the corresponding\n\
1069 item of each sequence, substituting None for missing values when not all\n\
1070 sequences have the same length. If the function is None, return a list of\n\
1071 the items of the sequence (or a list of tuples if more than one sequence).";
1074 static PyObject *
1075 builtin_setattr(PyObject *self, PyObject *args)
1077 PyObject *v;
1078 PyObject *name;
1079 PyObject *value;
1081 if (!PyArg_ParseTuple(args, "OOO:setattr", &v, &name, &value))
1082 return NULL;
1083 if (PyObject_SetAttr(v, name, value) != 0)
1084 return NULL;
1085 Py_INCREF(Py_None);
1086 return Py_None;
1089 static char setattr_doc[] =
1090 "setattr(object, name, value)\n\
1092 Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
1093 ``x.y = v''.";
1096 static PyObject *
1097 builtin_delattr(PyObject *self, PyObject *args)
1099 PyObject *v;
1100 PyObject *name;
1102 if (!PyArg_ParseTuple(args, "OO:delattr", &v, &name))
1103 return NULL;
1104 if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
1105 return NULL;
1106 Py_INCREF(Py_None);
1107 return Py_None;
1110 static char delattr_doc[] =
1111 "delattr(object, name)\n\
1113 Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
1114 ``del x.y''.";
1117 static PyObject *
1118 builtin_hash(PyObject *self, PyObject *args)
1120 PyObject *v;
1121 long x;
1123 if (!PyArg_ParseTuple(args, "O:hash", &v))
1124 return NULL;
1125 x = PyObject_Hash(v);
1126 if (x == -1)
1127 return NULL;
1128 return PyInt_FromLong(x);
1131 static char hash_doc[] =
1132 "hash(object) -> integer\n\
1134 Return a hash value for the object. Two objects with the same value have\n\
1135 the same hash value. The reverse is not necessarily true, but likely.";
1138 static PyObject *
1139 builtin_hex(PyObject *self, PyObject *args)
1141 PyObject *v;
1142 PyNumberMethods *nb;
1144 if (!PyArg_ParseTuple(args, "O:hex", &v))
1145 return NULL;
1147 if ((nb = v->ob_type->tp_as_number) == NULL ||
1148 nb->nb_hex == NULL) {
1149 PyErr_SetString(PyExc_TypeError,
1150 "hex() argument can't be converted to hex");
1151 return NULL;
1153 return (*nb->nb_hex)(v);
1156 static char hex_doc[] =
1157 "hex(number) -> string\n\
1159 Return the hexadecimal representation of an integer or long integer.";
1162 static PyObject *builtin_raw_input(PyObject *, PyObject *);
1164 static PyObject *
1165 builtin_input(PyObject *self, PyObject *args)
1167 PyObject *line;
1168 char *str;
1169 PyObject *res;
1170 PyObject *globals, *locals;
1172 line = builtin_raw_input(self, args);
1173 if (line == NULL)
1174 return line;
1175 if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
1176 return NULL;
1177 while (*str == ' ' || *str == '\t')
1178 str++;
1179 globals = PyEval_GetGlobals();
1180 locals = PyEval_GetLocals();
1181 if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
1182 if (PyDict_SetItemString(globals, "__builtins__",
1183 PyEval_GetBuiltins()) != 0)
1184 return NULL;
1186 res = PyRun_String(str, Py_eval_input, globals, locals);
1187 Py_DECREF(line);
1188 return res;
1191 static char input_doc[] =
1192 "input([prompt]) -> value\n\
1194 Equivalent to eval(raw_input(prompt)).";
1197 static PyObject *
1198 builtin_intern(PyObject *self, PyObject *args)
1200 PyObject *s;
1201 if (!PyArg_ParseTuple(args, "S:intern", &s))
1202 return NULL;
1203 Py_INCREF(s);
1204 PyString_InternInPlace(&s);
1205 return s;
1208 static char intern_doc[] =
1209 "intern(string) -> string\n\
1211 ``Intern'' the given string. This enters the string in the (global)\n\
1212 table of interned strings whose purpose is to speed up dictionary lookups.\n\
1213 Return the string itself or the previously interned string object with the\n\
1214 same value.";
1217 static PyObject *
1218 builtin_int(PyObject *self, PyObject *args)
1220 PyObject *v;
1221 int base = -909; /* unlikely! */
1223 if (!PyArg_ParseTuple(args, "O|i:int", &v, &base))
1224 return NULL;
1225 if (base == -909)
1226 return PyNumber_Int(v);
1227 else if (PyString_Check(v))
1228 return PyInt_FromString(PyString_AS_STRING(v), NULL, base);
1229 else if (PyUnicode_Check(v))
1230 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(v),
1231 PyUnicode_GET_SIZE(v),
1232 base);
1233 else {
1234 PyErr_SetString(PyExc_TypeError,
1235 "int() can't convert non-string with explicit base");
1236 return NULL;
1240 static char int_doc[] =
1241 "int(x[, base]) -> integer\n\
1243 Convert a string or number to an integer, if possible. A floating point\n\
1244 argument will be truncated towards zero (this does not include a string\n\
1245 representation of a floating point number!) When converting a string, use\n\
1246 the optional base. It is an error to supply a base when converting a\n\
1247 non-string.";
1250 static PyObject *
1251 builtin_long(PyObject *self, PyObject *args)
1253 PyObject *v;
1254 int base = -909; /* unlikely! */
1256 if (!PyArg_ParseTuple(args, "O|i:long", &v, &base))
1257 return NULL;
1258 if (base == -909)
1259 return PyNumber_Long(v);
1260 else if (PyString_Check(v))
1261 return PyLong_FromString(PyString_AS_STRING(v), NULL, base);
1262 else if (PyUnicode_Check(v))
1263 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(v),
1264 PyUnicode_GET_SIZE(v),
1265 base);
1266 else {
1267 PyErr_SetString(PyExc_TypeError,
1268 "long() can't convert non-string with explicit base");
1269 return NULL;
1273 static char long_doc[] =
1274 "long(x) -> long integer\n\
1275 long(x, base) -> long integer\n\
1277 Convert a string or number to a long integer, if possible. A floating\n\
1278 point argument will be truncated towards zero (this does not include a\n\
1279 string representation of a floating point number!) When converting a\n\
1280 string, use the given base. It is an error to supply a base when\n\
1281 converting a non-string.";
1284 static PyObject *
1285 builtin_float(PyObject *self, PyObject *args)
1287 PyObject *v;
1289 if (!PyArg_ParseTuple(args, "O:float", &v))
1290 return NULL;
1291 if (PyString_Check(v))
1292 return PyFloat_FromString(v, NULL);
1293 return PyNumber_Float(v);
1296 static char float_doc[] =
1297 "float(x) -> floating point number\n\
1299 Convert a string or number to a floating point number, if possible.";
1302 static PyObject *
1303 builtin_len(PyObject *self, PyObject *args)
1305 PyObject *v;
1306 long res;
1308 if (!PyArg_ParseTuple(args, "O:len", &v))
1309 return NULL;
1310 res = PyObject_Size(v);
1311 if (res < 0 && PyErr_Occurred())
1312 return NULL;
1313 return PyInt_FromLong(res);
1316 static char len_doc[] =
1317 "len(object) -> integer\n\
1319 Return the number of items of a sequence or mapping.";
1322 static PyObject *
1323 builtin_list(PyObject *self, PyObject *args)
1325 PyObject *v;
1327 if (!PyArg_ParseTuple(args, "O:list", &v))
1328 return NULL;
1329 return PySequence_List(v);
1332 static char list_doc[] =
1333 "list(sequence) -> list\n\
1335 Return a new list whose items are the same as those of the argument sequence.";
1338 static PyObject *
1339 builtin_slice(PyObject *self, PyObject *args)
1341 PyObject *start, *stop, *step;
1343 start = stop = step = NULL;
1345 if (!PyArg_ParseTuple(args, "O|OO:slice", &start, &stop, &step))
1346 return NULL;
1348 /* This swapping of stop and start is to maintain similarity with
1349 range(). */
1350 if (stop == NULL) {
1351 stop = start;
1352 start = NULL;
1354 return PySlice_New(start, stop, step);
1357 static char slice_doc[] =
1358 "slice([start,] stop[, step]) -> slice object\n\
1360 Create a slice object. This is used for slicing by the Numeric extensions.";
1363 static PyObject *
1364 builtin_locals(PyObject *self, PyObject *args)
1366 PyObject *d;
1368 if (!PyArg_ParseTuple(args, ":locals"))
1369 return NULL;
1370 d = PyEval_GetLocals();
1371 Py_INCREF(d);
1372 return d;
1375 static char locals_doc[] =
1376 "locals() -> dictionary\n\
1378 Return the dictionary containing the current scope's local variables.";
1381 static PyObject *
1382 min_max(PyObject *args, int op)
1384 int i;
1385 PyObject *v, *w, *x;
1386 PySequenceMethods *sq;
1388 if (PyTuple_Size(args) > 1)
1389 v = args;
1390 else if (!PyArg_ParseTuple(args, "O:min/max", &v))
1391 return NULL;
1392 sq = v->ob_type->tp_as_sequence;
1393 if (sq == NULL || sq->sq_item == NULL) {
1394 PyErr_SetString(PyExc_TypeError,
1395 "min() or max() arg must be a sequence");
1396 return NULL;
1398 w = NULL;
1399 for (i = 0; ; i++) {
1400 x = (*sq->sq_item)(v, i); /* Implies INCREF */
1401 if (x == NULL) {
1402 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1403 PyErr_Clear();
1404 break;
1406 Py_XDECREF(w);
1407 return NULL;
1409 if (w == NULL)
1410 w = x;
1411 else {
1412 int cmp = PyObject_RichCompareBool(x, w, op);
1413 if (cmp > 0) {
1414 Py_DECREF(w);
1415 w = x;
1417 else if (cmp < 0) {
1418 Py_DECREF(x);
1419 Py_XDECREF(w);
1420 return NULL;
1422 else
1423 Py_DECREF(x);
1426 if (w == NULL)
1427 PyErr_SetString(PyExc_ValueError,
1428 "min() or max() arg is an empty sequence");
1429 return w;
1432 static PyObject *
1433 builtin_min(PyObject *self, PyObject *v)
1435 return min_max(v, Py_LT);
1438 static char min_doc[] =
1439 "min(sequence) -> value\n\
1440 min(a, b, c, ...) -> value\n\
1442 With a single sequence argument, return its smallest item.\n\
1443 With two or more arguments, return the smallest argument.";
1446 static PyObject *
1447 builtin_max(PyObject *self, PyObject *v)
1449 return min_max(v, Py_GT);
1452 static char max_doc[] =
1453 "max(sequence) -> value\n\
1454 max(a, b, c, ...) -> value\n\
1456 With a single sequence argument, return its largest item.\n\
1457 With two or more arguments, return the largest argument.";
1460 static PyObject *
1461 builtin_oct(PyObject *self, PyObject *args)
1463 PyObject *v;
1464 PyNumberMethods *nb;
1466 if (!PyArg_ParseTuple(args, "O:oct", &v))
1467 return NULL;
1468 if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
1469 nb->nb_oct == NULL) {
1470 PyErr_SetString(PyExc_TypeError,
1471 "oct() argument can't be converted to oct");
1472 return NULL;
1474 return (*nb->nb_oct)(v);
1477 static char oct_doc[] =
1478 "oct(number) -> string\n\
1480 Return the octal representation of an integer or long integer.";
1483 static PyObject *
1484 builtin_open(PyObject *self, PyObject *args)
1486 char *name;
1487 char *mode = "r";
1488 int bufsize = -1;
1489 PyObject *f;
1491 if (!PyArg_ParseTuple(args, "s|si:open", &name, &mode, &bufsize))
1492 return NULL;
1493 f = PyFile_FromString(name, mode);
1494 if (f != NULL)
1495 PyFile_SetBufSize(f, bufsize);
1496 return f;
1499 static char open_doc[] =
1500 "open(filename[, mode[, buffering]]) -> file object\n\
1502 Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n\
1503 writing or appending. The file will be created if it doesn't exist\n\
1504 when opened for writing or appending; it will be truncated when\n\
1505 opened for writing. Add a 'b' to the mode for binary files.\n\
1506 Add a '+' to the mode to allow simultaneous reading and writing.\n\
1507 If the buffering argument is given, 0 means unbuffered, 1 means line\n\
1508 buffered, and larger numbers specify the buffer size.";
1511 static PyObject *
1512 builtin_ord(PyObject *self, PyObject *args)
1514 PyObject *obj;
1515 long ord;
1516 int size;
1518 if (!PyArg_ParseTuple(args, "O:ord", &obj))
1519 return NULL;
1521 if (PyString_Check(obj)) {
1522 size = PyString_GET_SIZE(obj);
1523 if (size == 1) {
1524 ord = (long)((unsigned char)*PyString_AS_STRING(obj));
1525 return PyInt_FromLong(ord);
1527 } else if (PyUnicode_Check(obj)) {
1528 size = PyUnicode_GET_SIZE(obj);
1529 if (size == 1) {
1530 ord = (long)*PyUnicode_AS_UNICODE(obj);
1531 return PyInt_FromLong(ord);
1533 } else {
1534 PyErr_Format(PyExc_TypeError,
1535 "ord() expected string of length 1, but " \
1536 "%.200s found", obj->ob_type->tp_name);
1537 return NULL;
1540 PyErr_Format(PyExc_TypeError,
1541 "ord() expected a character, "
1542 "but string of length %d found",
1543 size);
1544 return NULL;
1547 static char ord_doc[] =
1548 "ord(c) -> integer\n\
1550 Return the integer ordinal of a one-character string.";
1553 static PyObject *
1554 builtin_pow(PyObject *self, PyObject *args)
1556 PyObject *v, *w, *z = Py_None;
1558 if (!PyArg_ParseTuple(args, "OO|O:pow", &v, &w, &z))
1559 return NULL;
1560 return PyNumber_Power(v, w, z);
1563 static char pow_doc[] =
1564 "pow(x, y[, z]) -> number\n\
1566 With two arguments, equivalent to x**y. With three arguments,\n\
1567 equivalent to (x**y) % z, but may be more efficient (e.g. for longs).";
1570 /* Return number of items in range/xrange (lo, hi, step). step > 0
1571 * required. Return a value < 0 if & only if the true value is too
1572 * large to fit in a signed long.
1574 static long
1575 get_len_of_range(long lo, long hi, long step)
1577 /* -------------------------------------------------------------
1578 If lo >= hi, the range is empty.
1579 Else if n values are in the range, the last one is
1580 lo + (n-1)*step, which must be <= hi-1. Rearranging,
1581 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
1582 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
1583 the RHS is non-negative and so truncation is the same as the
1584 floor. Letting M be the largest positive long, the worst case
1585 for the RHS numerator is hi=M, lo=-M-1, and then
1586 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
1587 precision to compute the RHS exactly.
1588 ---------------------------------------------------------------*/
1589 long n = 0;
1590 if (lo < hi) {
1591 unsigned long uhi = (unsigned long)hi;
1592 unsigned long ulo = (unsigned long)lo;
1593 unsigned long diff = uhi - ulo - 1;
1594 n = (long)(diff / (unsigned long)step + 1);
1596 return n;
1599 static PyObject *
1600 builtin_range(PyObject *self, PyObject *args)
1602 long ilow = 0, ihigh = 0, istep = 1;
1603 long bign;
1604 int i, n;
1606 PyObject *v;
1608 if (PyTuple_Size(args) <= 1) {
1609 if (!PyArg_ParseTuple(args,
1610 "l;range() requires 1-3 int arguments",
1611 &ihigh))
1612 return NULL;
1614 else {
1615 if (!PyArg_ParseTuple(args,
1616 "ll|l;range() requires 1-3 int arguments",
1617 &ilow, &ihigh, &istep))
1618 return NULL;
1620 if (istep == 0) {
1621 PyErr_SetString(PyExc_ValueError, "range() arg 3 must not be zero");
1622 return NULL;
1624 if (istep > 0)
1625 bign = get_len_of_range(ilow, ihigh, istep);
1626 else
1627 bign = get_len_of_range(ihigh, ilow, -istep);
1628 n = (int)bign;
1629 if (bign < 0 || (long)n != bign) {
1630 PyErr_SetString(PyExc_OverflowError,
1631 "range() result has too many items");
1632 return NULL;
1634 v = PyList_New(n);
1635 if (v == NULL)
1636 return NULL;
1637 for (i = 0; i < n; i++) {
1638 PyObject *w = PyInt_FromLong(ilow);
1639 if (w == NULL) {
1640 Py_DECREF(v);
1641 return NULL;
1643 PyList_SET_ITEM(v, i, w);
1644 ilow += istep;
1646 return v;
1649 static char range_doc[] =
1650 "range([start,] stop[, step]) -> list of integers\n\
1652 Return a list containing an arithmetic progression of integers.\n\
1653 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
1654 When step is given, it specifies the increment (or decrement).\n\
1655 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
1656 These are exactly the valid indices for a list of 4 elements.";
1659 static PyObject *
1660 builtin_xrange(PyObject *self, PyObject *args)
1662 long ilow = 0, ihigh = 0, istep = 1;
1663 long n;
1665 if (PyTuple_Size(args) <= 1) {
1666 if (!PyArg_ParseTuple(args,
1667 "l;xrange() requires 1-3 int arguments",
1668 &ihigh))
1669 return NULL;
1671 else {
1672 if (!PyArg_ParseTuple(args,
1673 "ll|l;xrange() requires 1-3 int arguments",
1674 &ilow, &ihigh, &istep))
1675 return NULL;
1677 if (istep == 0) {
1678 PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
1679 return NULL;
1681 if (istep > 0)
1682 n = get_len_of_range(ilow, ihigh, istep);
1683 else
1684 n = get_len_of_range(ihigh, ilow, -istep);
1685 if (n < 0) {
1686 PyErr_SetString(PyExc_OverflowError,
1687 "xrange() result has too many items");
1688 return NULL;
1690 return PyRange_New(ilow, n, istep, 1);
1693 static char xrange_doc[] =
1694 "xrange([start,] stop[, step]) -> xrange object\n\
1696 Like range(), but instead of returning a list, returns an object that\n\
1697 generates the numbers in the range on demand. This is slightly slower\n\
1698 than range() but more memory efficient.";
1701 static PyObject *
1702 builtin_raw_input(PyObject *self, PyObject *args)
1704 PyObject *v = NULL;
1705 PyObject *f;
1707 if (!PyArg_ParseTuple(args, "|O:[raw_]input", &v))
1708 return NULL;
1709 if (PyFile_AsFile(PySys_GetObject("stdin")) == stdin &&
1710 PyFile_AsFile(PySys_GetObject("stdout")) == stdout &&
1711 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1712 PyObject *po;
1713 char *prompt;
1714 char *s;
1715 PyObject *result;
1716 if (v != NULL) {
1717 po = PyObject_Str(v);
1718 if (po == NULL)
1719 return NULL;
1720 prompt = PyString_AsString(po);
1721 if (prompt == NULL)
1722 return NULL;
1724 else {
1725 po = NULL;
1726 prompt = "";
1728 s = PyOS_Readline(prompt);
1729 Py_XDECREF(po);
1730 if (s == NULL) {
1731 PyErr_SetNone(PyExc_KeyboardInterrupt);
1732 return NULL;
1734 if (*s == '\0') {
1735 PyErr_SetNone(PyExc_EOFError);
1736 result = NULL;
1738 else { /* strip trailing '\n' */
1739 size_t len = strlen(s);
1740 if (len > INT_MAX) {
1741 PyErr_SetString(PyExc_OverflowError, "input too long");
1742 result = NULL;
1744 else {
1745 result = PyString_FromStringAndSize(s, (int)(len-1));
1748 PyMem_FREE(s);
1749 return result;
1751 if (v != NULL) {
1752 f = PySys_GetObject("stdout");
1753 if (f == NULL) {
1754 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
1755 return NULL;
1757 if (Py_FlushLine() != 0 ||
1758 PyFile_WriteObject(v, f, Py_PRINT_RAW) != 0)
1759 return NULL;
1761 f = PySys_GetObject("stdin");
1762 if (f == NULL) {
1763 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdin");
1764 return NULL;
1766 return PyFile_GetLine(f, -1);
1769 static char raw_input_doc[] =
1770 "raw_input([prompt]) -> string\n\
1772 Read a string from standard input. The trailing newline is stripped.\n\
1773 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
1774 On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
1775 is printed without a trailing newline before reading.";
1778 static PyObject *
1779 builtin_reduce(PyObject *self, PyObject *args)
1781 PyObject *seq, *func, *result = NULL;
1782 PySequenceMethods *sqf;
1783 register int i;
1785 if (!PyArg_ParseTuple(args, "OO|O:reduce", &func, &seq, &result))
1786 return NULL;
1787 if (result != NULL)
1788 Py_INCREF(result);
1790 sqf = seq->ob_type->tp_as_sequence;
1791 if (sqf == NULL || sqf->sq_item == NULL) {
1792 PyErr_SetString(PyExc_TypeError,
1793 "reduce() arg 2 must be a sequence");
1794 return NULL;
1797 if ((args = PyTuple_New(2)) == NULL)
1798 goto Fail;
1800 for (i = 0; ; ++i) {
1801 PyObject *op2;
1803 if (args->ob_refcnt > 1) {
1804 Py_DECREF(args);
1805 if ((args = PyTuple_New(2)) == NULL)
1806 goto Fail;
1809 if ((op2 = (*sqf->sq_item)(seq, i)) == NULL) {
1810 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1811 PyErr_Clear();
1812 break;
1814 goto Fail;
1817 if (result == NULL)
1818 result = op2;
1819 else {
1820 PyTuple_SetItem(args, 0, result);
1821 PyTuple_SetItem(args, 1, op2);
1822 if ((result = PyEval_CallObject(func, args)) == NULL)
1823 goto Fail;
1827 Py_DECREF(args);
1829 if (result == NULL)
1830 PyErr_SetString(PyExc_TypeError,
1831 "reduce() of empty sequence with no initial value");
1833 return result;
1835 Fail:
1836 Py_XDECREF(args);
1837 Py_XDECREF(result);
1838 return NULL;
1841 static char reduce_doc[] =
1842 "reduce(function, sequence[, initial]) -> value\n\
1844 Apply a function of two arguments cumulatively to the items of a sequence,\n\
1845 from left to right, so as to reduce the sequence to a single value.\n\
1846 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
1847 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
1848 of the sequence in the calculation, and serves as a default when the\n\
1849 sequence is empty.";
1852 static PyObject *
1853 builtin_reload(PyObject *self, PyObject *args)
1855 PyObject *v;
1857 if (!PyArg_ParseTuple(args, "O:reload", &v))
1858 return NULL;
1859 return PyImport_ReloadModule(v);
1862 static char reload_doc[] =
1863 "reload(module) -> module\n\
1865 Reload the module. The module must have been successfully imported before.";
1868 static PyObject *
1869 builtin_repr(PyObject *self, PyObject *args)
1871 PyObject *v;
1873 if (!PyArg_ParseTuple(args, "O:repr", &v))
1874 return NULL;
1875 return PyObject_Repr(v);
1878 static char repr_doc[] =
1879 "repr(object) -> string\n\
1881 Return the canonical string representation of the object.\n\
1882 For most object types, eval(repr(object)) == object.";
1885 static PyObject *
1886 builtin_round(PyObject *self, PyObject *args)
1888 double x;
1889 double f;
1890 int ndigits = 0;
1891 int i;
1893 if (!PyArg_ParseTuple(args, "d|i:round", &x, &ndigits))
1894 return NULL;
1895 f = 1.0;
1896 i = abs(ndigits);
1897 while (--i >= 0)
1898 f = f*10.0;
1899 if (ndigits < 0)
1900 x /= f;
1901 else
1902 x *= f;
1903 if (x >= 0.0)
1904 x = floor(x + 0.5);
1905 else
1906 x = ceil(x - 0.5);
1907 if (ndigits < 0)
1908 x *= f;
1909 else
1910 x /= f;
1911 return PyFloat_FromDouble(x);
1914 static char round_doc[] =
1915 "round(number[, ndigits]) -> floating point number\n\
1917 Round a number to a given precision in decimal digits (default 0 digits).\n\
1918 This always returns a floating point number. Precision may be negative.";
1921 static PyObject *
1922 builtin_str(PyObject *self, PyObject *args)
1924 PyObject *v;
1926 if (!PyArg_ParseTuple(args, "O:str", &v))
1927 return NULL;
1928 return PyObject_Str(v);
1931 static char str_doc[] =
1932 "str(object) -> string\n\
1934 Return a nice string representation of the object.\n\
1935 If the argument is a string, the return value is the same object.";
1938 static PyObject *
1939 builtin_tuple(PyObject *self, PyObject *args)
1941 PyObject *v;
1943 if (!PyArg_ParseTuple(args, "O:tuple", &v))
1944 return NULL;
1945 return PySequence_Tuple(v);
1948 static char tuple_doc[] =
1949 "tuple(sequence) -> list\n\
1951 Return a tuple whose items are the same as those of the argument sequence.\n\
1952 If the argument is a tuple, the return value is the same object.";
1955 static PyObject *
1956 builtin_type(PyObject *self, PyObject *args)
1958 PyObject *v;
1960 if (!PyArg_ParseTuple(args, "O:type", &v))
1961 return NULL;
1962 v = (PyObject *)v->ob_type;
1963 Py_INCREF(v);
1964 return v;
1967 static char type_doc[] =
1968 "type(object) -> type object\n\
1970 Return the type of the object.";
1973 static PyObject *
1974 builtin_vars(PyObject *self, PyObject *args)
1976 PyObject *v = NULL;
1977 PyObject *d;
1979 if (!PyArg_ParseTuple(args, "|O:vars", &v))
1980 return NULL;
1981 if (v == NULL) {
1982 d = PyEval_GetLocals();
1983 if (d == NULL) {
1984 if (!PyErr_Occurred())
1985 PyErr_SetString(PyExc_SystemError,
1986 "no locals!?");
1988 else
1989 Py_INCREF(d);
1991 else {
1992 d = PyObject_GetAttrString(v, "__dict__");
1993 if (d == NULL) {
1994 PyErr_SetString(PyExc_TypeError,
1995 "vars() argument must have __dict__ attribute");
1996 return NULL;
1999 return d;
2002 static char vars_doc[] =
2003 "vars([object]) -> dictionary\n\
2005 Without arguments, equivalent to locals().\n\
2006 With an argument, equivalent to object.__dict__.";
2008 static int
2009 abstract_issubclass(PyObject *derived, PyObject *cls, int first)
2011 static PyObject *__bases__ = NULL;
2012 PyObject *bases;
2013 int i, n;
2014 int r = 0;
2016 if (__bases__ == NULL) {
2017 __bases__ = PyString_FromString("__bases__");
2018 if (__bases__ == NULL)
2019 return -1;
2022 if (first) {
2023 bases = PyObject_GetAttr(cls, __bases__);
2024 if (bases == NULL || !PyTuple_Check(bases)) {
2025 Py_XDECREF(bases);
2026 PyErr_SetString(PyExc_TypeError,
2027 "issubclass() arg 2 must be a class");
2028 return -1;
2030 Py_DECREF(bases);
2033 if (derived == cls)
2034 return 1;
2036 bases = PyObject_GetAttr(derived, __bases__);
2037 if (bases == NULL || !PyTuple_Check(bases)) {
2038 Py_XDECREF(bases);
2039 PyErr_SetString(PyExc_TypeError,
2040 "issubclass() arg 1 must be a class");
2041 return -1;
2044 n = PyTuple_GET_SIZE(bases);
2045 for (i = 0; i < n; i++) {
2046 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls, 0);
2047 if (r != 0)
2048 break;
2051 Py_DECREF(bases);
2053 return r;
2056 static PyObject *
2057 builtin_isinstance(PyObject *self, PyObject *args)
2059 PyObject *inst;
2060 PyObject *cls;
2061 PyObject *icls;
2062 static PyObject *__class__ = NULL;
2063 int retval = 0;
2065 if (!PyArg_ParseTuple(args, "OO:isinstance", &inst, &cls))
2066 return NULL;
2068 if (PyClass_Check(cls)) {
2069 if (PyInstance_Check(inst)) {
2070 PyObject *inclass =
2071 (PyObject*)((PyInstanceObject*)inst)->in_class;
2072 retval = PyClass_IsSubclass(inclass, cls);
2075 else if (PyType_Check(cls)) {
2076 retval = ((PyObject *)(inst->ob_type) == cls);
2078 else if (!PyInstance_Check(inst)) {
2079 if (__class__ == NULL) {
2080 __class__ = PyString_FromString("__class__");
2081 if (__class__ == NULL)
2082 return NULL;
2084 icls = PyObject_GetAttr(inst, __class__);
2085 if (icls != NULL) {
2086 retval = abstract_issubclass(icls, cls, 1);
2087 Py_DECREF(icls);
2088 if (retval < 0 &&
2089 !PyErr_ExceptionMatches(PyExc_TypeError))
2090 return NULL;
2092 else
2093 retval = -1;
2095 else
2096 retval = -1;
2098 if (retval < 0) {
2099 PyErr_SetString(PyExc_TypeError,
2100 "isinstance() arg 2 must be a class or type");
2101 return NULL;
2103 return PyInt_FromLong(retval);
2106 static char isinstance_doc[] =
2107 "isinstance(object, class-or-type) -> Boolean\n\
2109 Return whether an object is an instance of a class or of a subclass thereof.\n\
2110 With a type as second argument, return whether that is the object's type.";
2113 static PyObject *
2114 builtin_issubclass(PyObject *self, PyObject *args)
2116 PyObject *derived;
2117 PyObject *cls;
2118 int retval;
2120 if (!PyArg_ParseTuple(args, "OO:issubclass", &derived, &cls))
2121 return NULL;
2123 if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
2124 retval = abstract_issubclass(derived, cls, 1);
2125 if (retval < 0)
2126 return NULL;
2128 else {
2129 /* shortcut */
2130 if (!(retval = (derived == cls)))
2131 retval = PyClass_IsSubclass(derived, cls);
2134 return PyInt_FromLong(retval);
2137 static char issubclass_doc[] =
2138 "issubclass(C, B) -> Boolean\n\
2140 Return whether class C is a subclass (i.e., a derived class) of class B.";
2143 static PyObject*
2144 builtin_zip(PyObject *self, PyObject *args)
2146 PyObject *ret;
2147 int itemsize = PySequence_Length(args);
2148 int i, j;
2150 if (itemsize < 1) {
2151 PyErr_SetString(PyExc_TypeError,
2152 "zip() requires at least one sequence");
2153 return NULL;
2155 /* args must be a tuple */
2156 assert(PyTuple_Check(args));
2158 if ((ret = PyList_New(0)) == NULL)
2159 return NULL;
2161 for (i = 0;; i++) {
2162 PyObject *next = PyTuple_New(itemsize);
2163 if (!next) {
2164 Py_DECREF(ret);
2165 return NULL;
2167 for (j = 0; j < itemsize; j++) {
2168 PyObject *seq = PyTuple_GET_ITEM(args, j);
2169 PyObject *item = PySequence_GetItem(seq, i);
2171 if (!item) {
2172 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2173 PyErr_Clear();
2174 Py_DECREF(next);
2175 return ret;
2177 Py_DECREF(next);
2178 Py_DECREF(ret);
2179 return NULL;
2181 PyTuple_SET_ITEM(next, j, item);
2183 PyList_Append(ret, next);
2184 Py_DECREF(next);
2186 /* no return */
2190 static char zip_doc[] =
2191 "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
2193 Return a list of tuples, where each tuple contains the i-th element\n\
2194 from each of the argument sequences. The returned list is truncated\n\
2195 in length to the length of the shortest argument sequence.";
2198 static PyMethodDef builtin_methods[] = {
2199 {"__import__", builtin___import__, 1, import_doc},
2200 {"abs", builtin_abs, 1, abs_doc},
2201 {"apply", builtin_apply, 1, apply_doc},
2202 {"buffer", builtin_buffer, 1, buffer_doc},
2203 {"callable", builtin_callable, 1, callable_doc},
2204 {"chr", builtin_chr, 1, chr_doc},
2205 {"cmp", builtin_cmp, 1, cmp_doc},
2206 {"coerce", builtin_coerce, 1, coerce_doc},
2207 {"compile", builtin_compile, 1, compile_doc},
2208 #ifndef WITHOUT_COMPLEX
2209 {"complex", builtin_complex, 1, complex_doc},
2210 #endif
2211 {"delattr", builtin_delattr, 1, delattr_doc},
2212 {"dir", builtin_dir, 1, dir_doc},
2213 {"divmod", builtin_divmod, 1, divmod_doc},
2214 {"eval", builtin_eval, 1, eval_doc},
2215 {"execfile", builtin_execfile, 1, execfile_doc},
2216 {"filter", builtin_filter, 1, filter_doc},
2217 {"float", builtin_float, 1, float_doc},
2218 {"getattr", builtin_getattr, 1, getattr_doc},
2219 {"globals", builtin_globals, 1, globals_doc},
2220 {"hasattr", builtin_hasattr, 1, hasattr_doc},
2221 {"hash", builtin_hash, 1, hash_doc},
2222 {"hex", builtin_hex, 1, hex_doc},
2223 {"id", builtin_id, 1, id_doc},
2224 {"input", builtin_input, 1, input_doc},
2225 {"intern", builtin_intern, 1, intern_doc},
2226 {"int", builtin_int, 1, int_doc},
2227 {"isinstance", builtin_isinstance, 1, isinstance_doc},
2228 {"issubclass", builtin_issubclass, 1, issubclass_doc},
2229 {"len", builtin_len, 1, len_doc},
2230 {"list", builtin_list, 1, list_doc},
2231 {"locals", builtin_locals, 1, locals_doc},
2232 {"long", builtin_long, 1, long_doc},
2233 {"map", builtin_map, 1, map_doc},
2234 {"max", builtin_max, 1, max_doc},
2235 {"min", builtin_min, 1, min_doc},
2236 {"oct", builtin_oct, 1, oct_doc},
2237 {"open", builtin_open, 1, open_doc},
2238 {"ord", builtin_ord, 1, ord_doc},
2239 {"pow", builtin_pow, 1, pow_doc},
2240 {"range", builtin_range, 1, range_doc},
2241 {"raw_input", builtin_raw_input, 1, raw_input_doc},
2242 {"reduce", builtin_reduce, 1, reduce_doc},
2243 {"reload", builtin_reload, 1, reload_doc},
2244 {"repr", builtin_repr, 1, repr_doc},
2245 {"round", builtin_round, 1, round_doc},
2246 {"setattr", builtin_setattr, 1, setattr_doc},
2247 {"slice", builtin_slice, 1, slice_doc},
2248 {"str", builtin_str, 1, str_doc},
2249 {"tuple", builtin_tuple, 1, tuple_doc},
2250 {"type", builtin_type, 1, type_doc},
2251 {"unicode", builtin_unicode, 1, unicode_doc},
2252 {"unichr", builtin_unichr, 1, unichr_doc},
2253 {"vars", builtin_vars, 1, vars_doc},
2254 {"xrange", builtin_xrange, 1, xrange_doc},
2255 {"zip", builtin_zip, 1, zip_doc},
2256 {NULL, NULL},
2259 static char builtin_doc[] =
2260 "Built-in functions, exceptions, and other objects.\n\
2262 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.";
2264 PyObject *
2265 _PyBuiltin_Init(void)
2267 PyObject *mod, *dict, *debug;
2268 mod = Py_InitModule4("__builtin__", builtin_methods,
2269 builtin_doc, (PyObject *)NULL,
2270 PYTHON_API_VERSION);
2271 if (mod == NULL)
2272 return NULL;
2273 dict = PyModule_GetDict(mod);
2274 if (PyDict_SetItemString(dict, "None", Py_None) < 0)
2275 return NULL;
2276 if (PyDict_SetItemString(dict, "Ellipsis", Py_Ellipsis) < 0)
2277 return NULL;
2278 if (PyDict_SetItemString(dict, "NotImplemented",
2279 Py_NotImplemented) < 0)
2280 return NULL;
2281 debug = PyInt_FromLong(Py_OptimizeFlag == 0);
2282 if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
2283 Py_XDECREF(debug);
2284 return NULL;
2286 Py_XDECREF(debug);
2288 return mod;
2291 /* Helper for filter(): filter a tuple through a function */
2293 static PyObject *
2294 filtertuple(PyObject *func, PyObject *tuple)
2296 PyObject *result;
2297 register int i, j;
2298 int len = PyTuple_Size(tuple);
2300 if (len == 0) {
2301 Py_INCREF(tuple);
2302 return tuple;
2305 if ((result = PyTuple_New(len)) == NULL)
2306 return NULL;
2308 for (i = j = 0; i < len; ++i) {
2309 PyObject *item, *good;
2310 int ok;
2312 if ((item = PyTuple_GetItem(tuple, i)) == NULL)
2313 goto Fail_1;
2314 if (func == Py_None) {
2315 Py_INCREF(item);
2316 good = item;
2318 else {
2319 PyObject *arg = Py_BuildValue("(O)", item);
2320 if (arg == NULL)
2321 goto Fail_1;
2322 good = PyEval_CallObject(func, arg);
2323 Py_DECREF(arg);
2324 if (good == NULL)
2325 goto Fail_1;
2327 ok = PyObject_IsTrue(good);
2328 Py_DECREF(good);
2329 if (ok) {
2330 Py_INCREF(item);
2331 if (PyTuple_SetItem(result, j++, item) < 0)
2332 goto Fail_1;
2336 if (_PyTuple_Resize(&result, j, 0) < 0)
2337 return NULL;
2339 return result;
2341 Fail_1:
2342 Py_DECREF(result);
2343 return NULL;
2347 /* Helper for filter(): filter a string through a function */
2349 static PyObject *
2350 filterstring(PyObject *func, PyObject *strobj)
2352 PyObject *result;
2353 register int i, j;
2354 int len = PyString_Size(strobj);
2356 if (func == Py_None) {
2357 /* No character is ever false -- share input string */
2358 Py_INCREF(strobj);
2359 return strobj;
2361 if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
2362 return NULL;
2364 for (i = j = 0; i < len; ++i) {
2365 PyObject *item, *arg, *good;
2366 int ok;
2368 item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
2369 if (item == NULL)
2370 goto Fail_1;
2371 arg = Py_BuildValue("(O)", item);
2372 Py_DECREF(item);
2373 if (arg == NULL)
2374 goto Fail_1;
2375 good = PyEval_CallObject(func, arg);
2376 Py_DECREF(arg);
2377 if (good == NULL)
2378 goto Fail_1;
2379 ok = PyObject_IsTrue(good);
2380 Py_DECREF(good);
2381 if (ok)
2382 PyString_AS_STRING((PyStringObject *)result)[j++] =
2383 PyString_AS_STRING((PyStringObject *)item)[0];
2386 if (j < len && _PyString_Resize(&result, j) < 0)
2387 return NULL;
2389 return result;
2391 Fail_1:
2392 Py_DECREF(result);
2393 return NULL;