future_builtins.c 2.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

/* future_builtins module */

/* This module provides functions that will be builtins in Python 3.0,
   but that conflict with builtins that already exist in Python
   2.x. */


#include "Python.h"

PyDoc_STRVAR(module_doc,
"This module provides functions that will be builtins in Python 3.0,\n\
but that conflict with builtins that already exist in Python 2.x.\n\
\n\
Functions:\n\
\n\
Neal Norwitz's avatar
Neal Norwitz committed
17
hex(arg) -- Returns the hexadecimal representation of an integer\n\
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
oct(arg) -- Returns the octal representation of an integer\n\
\n\
The typical usage of this module is to replace existing builtins in a\n\
module's namespace:\n \n\
from future_builtins import hex, oct\n");

static PyObject *
builtin_hex(PyObject *self, PyObject *v)
{
	return PyNumber_ToBase(v, 16);
}

PyDoc_STRVAR(hex_doc,
"hex(number) -> string\n\
\n\
Return the hexadecimal representation of an integer or long integer.");


static PyObject *
builtin_oct(PyObject *self, PyObject *v)
{
	return PyNumber_ToBase(v, 8);
}

PyDoc_STRVAR(oct_doc,
"oct(number) -> string\n\
\n\
Return the octal representation of an integer or long integer.");


48 49 50 51 52 53 54 55 56 57 58 59 60
static PyObject *
builtin_ascii(PyObject *self, PyObject *v)
{
	return PyObject_Repr(v);
}

PyDoc_STRVAR(ascii_doc,
"ascii(object) -> string\n\
\n\
Return the same as repr().  In Python 3.x, the repr() result will\n\
contain printable characters unescaped, while the ascii() result\n\
will have such characters backslash-escaped.");

61 62 63 64 65
/* List of functions exported by this module */

static PyMethodDef module_functions[] = {
 	{"hex",		builtin_hex,        METH_O, hex_doc},
 	{"oct",		builtin_oct,        METH_O, oct_doc},
66
	{"ascii",	builtin_ascii,      METH_O, ascii_doc},
67 68 69 70 71 72 73 74 75
	{NULL,		NULL}	/* Sentinel */
};


/* Initialize this module. */

PyMODINIT_FUNC
initfuture_builtins(void)
{
76 77 78
	PyObject *m, *itertools, *iter_func;
	char *it_funcs[] = {"imap", "ifilter", "izip", NULL};
	char **cur_func;
79 80 81 82 83

	m = Py_InitModule3("future_builtins", module_functions, module_doc);
	if (m == NULL)
		return;

84 85 86 87 88 89 90 91 92 93 94
	itertools = PyImport_ImportModuleNoBlock("itertools");
	if (itertools == NULL)
		return;

	for (cur_func = it_funcs; *cur_func; ++cur_func){
		iter_func = PyObject_GetAttrString(itertools, *cur_func);
		if (iter_func == NULL)
			return;
		PyModule_AddObject(m, *cur_func+1, iter_func);
	}
	Py_DECREF(itertools);
95 96
	/* any other initialization needed */
}