Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skip costly attribute check for unicode strings #434

Merged
merged 1 commit into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Unreleased
:issue:`401`
- The ``__version__`` attribute is deprecated. Use feature detection, or
``importlib.metadata.version("markupsafe")``, instead. :pr:`402`
- Improve speedups for plain strings by 30-40%. :pr:`434`


Version 2.1.5
Expand Down
21 changes: 14 additions & 7 deletions src/markupsafe/_speedups.c
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,13 @@ escape(PyObject *self, PyObject *text)
static PyObject *id_html;
PyObject *s = NULL, *rv = NULL, *html;

if (id_html == NULL) {
id_html = PyUnicode_InternFromString("__html__");
if (id_html == NULL) {
return NULL;
}
}
/* plain str instances can be escaped without further inspection */
if (PyUnicode_CheckExact(text)) {
s = escape_unicode((PyUnicodeObject*)text);
rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);
Py_DECREF(s);
return rv;
}

/* we don't have to escape integers, bools or floats */
if (PyLong_CheckExact(text) ||
Expand All @@ -203,7 +204,13 @@ escape(PyObject *self, PyObject *text)
return PyObject_CallFunctionObjArgs(markup, text, NULL);

/* if the object has an __html__ method that performs the escaping */
html = PyObject_GetAttr(text ,id_html);
if (id_html == NULL) {
id_html = PyUnicode_InternFromString("__html__");
if (id_html == NULL) {
return NULL;
}
}
html = PyObject_GetAttr(text, id_html);
if (html) {
s = PyObject_CallObject(html, NULL);
Py_DECREF(html);
Expand Down