There is also the excellent markupsafe package.
>>> from markupsafe import Markup, escape
>>> escape("<script>alert(document.cookie);</script>")
Markup(u'<script>alert(document.cookie);</script>')
The markupsafe
package is well engineered, and probably the most versatile and Pythonic way to go about escaping, IMHO, because:
Markup
) is a class derived from unicode (i.e. isinstance(escape('str'), unicode) == True
__html__
property) and template overloads (__html_format__
).