Skip to content

Commit

Permalink
Make the _speedups extension compatible with Python 3.
Browse files Browse the repository at this point in the history
--HG--
branch : trunk
  • Loading branch information
birkenfeld committed Feb 21, 2010
1 parent 17f5447 commit 05be95a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES
Expand Up @@ -10,6 +10,8 @@ Version 2.4
makes it possible to import or extend from a template object
that was passed to the template.

- the _speedups C extension now supports Python 3.

Version 2.3.1
-------------
(bugfix release, released on February 19th 2010)
Expand Down
40 changes: 39 additions & 1 deletion jinja2/_speedups.c
Expand Up @@ -123,7 +123,10 @@ escape(PyObject *self, PyObject *text)
PyObject *s = NULL, *rv = NULL, *html;

/* we don't have to escape integers, bools or floats */
if (PyInt_CheckExact(text) || PyLong_CheckExact(text) ||
if (PyLong_CheckExact(text) ||
#if PY_MAJOR_VERSION < 3
PyInt_CheckExact(text) ||
#endif
PyFloat_CheckExact(text) || PyBool_Check(text) ||
text == Py_None)
return PyObject_CallFunctionObjArgs(markup, text, NULL);
Expand All @@ -139,7 +142,11 @@ escape(PyObject *self, PyObject *text)
/* otherwise make the object unicode if it isn't, then escape */
PyErr_Clear();
if (!PyUnicode_Check(text)) {
#if PY_MAJOR_VERSION < 3
PyObject *unicode = PyObject_Unicode(text);
#else
PyObject *unicode = PyObject_Str(text);
#endif
if (!unicode)
return NULL;
s = escape_unicode((PyUnicodeObject*)unicode);
Expand All @@ -159,7 +166,11 @@ static PyObject*
soft_unicode(PyObject *self, PyObject *s)
{
if (!PyUnicode_Check(s))
#if PY_MAJOR_VERSION < 3
return PyObject_Unicode(s);
#else
return PyObject_Str(s);
#endif
Py_INCREF(s);
return s;
}
Expand Down Expand Up @@ -208,6 +219,8 @@ static PyMethodDef module_methods[] = {
};


#if PY_MAJOR_VERSION < 3

#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
Expand All @@ -219,3 +232,28 @@ init_speedups(void)

Py_InitModule3("jinja2._speedups", module_methods, "");
}

#else /* Python 3.x module initialization */

static struct PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
"jinja2._speedups",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};

PyMODINIT_FUNC
PyInit__speedups(void)
{
if (!init_constants())
return NULL;

return PyModule_Create(&module_definition);
}

#endif

0 comments on commit 05be95a

Please sign in to comment.