/Modules/future_builtins.c

http://unladen-swallow.googlecode.com/ · C · 96 lines · 68 code · 21 blank · 7 comment · 7 complexity · 00176b95d0c7a93313a0a99b07c8cb40 MD5 · raw file

  1. /* future_builtins module */
  2. /* This module provides functions that will be builtins in Python 3.0,
  3. but that conflict with builtins that already exist in Python
  4. 2.x. */
  5. #include "Python.h"
  6. PyDoc_STRVAR(module_doc,
  7. "This module provides functions that will be builtins in Python 3.0,\n\
  8. but that conflict with builtins that already exist in Python 2.x.\n\
  9. \n\
  10. Functions:\n\
  11. \n\
  12. hex(arg) -- Returns the hexadecimal representation of an integer\n\
  13. oct(arg) -- Returns the octal representation of an integer\n\
  14. \n\
  15. The typical usage of this module is to replace existing builtins in a\n\
  16. module's namespace:\n \n\
  17. from future_builtins import hex, oct\n");
  18. static PyObject *
  19. builtin_hex(PyObject *self, PyObject *v)
  20. {
  21. return PyNumber_ToBase(v, 16);
  22. }
  23. PyDoc_STRVAR(hex_doc,
  24. "hex(number) -> string\n\
  25. \n\
  26. Return the hexadecimal representation of an integer or long integer.");
  27. static PyObject *
  28. builtin_oct(PyObject *self, PyObject *v)
  29. {
  30. return PyNumber_ToBase(v, 8);
  31. }
  32. PyDoc_STRVAR(oct_doc,
  33. "oct(number) -> string\n\
  34. \n\
  35. Return the octal representation of an integer or long integer.");
  36. static PyObject *
  37. builtin_ascii(PyObject *self, PyObject *v)
  38. {
  39. return PyObject_Repr(v);
  40. }
  41. PyDoc_STRVAR(ascii_doc,
  42. "ascii(object) -> string\n\
  43. \n\
  44. Return the same as repr(). In Python 3.x, the repr() result will\n\
  45. contain printable characters unescaped, while the ascii() result\n\
  46. will have such characters backslash-escaped.");
  47. /* List of functions exported by this module */
  48. static PyMethodDef module_functions[] = {
  49. {"hex", builtin_hex, METH_O, hex_doc},
  50. {"oct", builtin_oct, METH_O, oct_doc},
  51. {"ascii", builtin_ascii, METH_O, ascii_doc},
  52. {NULL, NULL} /* Sentinel */
  53. };
  54. /* Initialize this module. */
  55. PyMODINIT_FUNC
  56. initfuture_builtins(void)
  57. {
  58. PyObject *m, *itertools, *iter_func;
  59. char *it_funcs[] = {"imap", "ifilter", "izip", NULL};
  60. char **cur_func;
  61. m = Py_InitModule3("future_builtins", module_functions, module_doc);
  62. if (m == NULL)
  63. return;
  64. itertools = PyImport_ImportModuleNoBlock("itertools");
  65. if (itertools == NULL)
  66. return;
  67. for (cur_func = it_funcs; *cur_func; ++cur_func){
  68. iter_func = PyObject_GetAttrString(itertools, *cur_func);
  69. if (iter_func == NULL)
  70. return;
  71. PyModule_AddObject(m, *cur_func+1, iter_func);
  72. }
  73. Py_DECREF(itertools);
  74. /* any other initialization needed */
  75. }