Skip to content

Commit

Permalink
python#18020: improve html.escape speed by an order of magnitude. Pat…
Browse files Browse the repository at this point in the history
…ch by Matt Bryant.
  • Loading branch information
ezio-melotti committed Jul 7, 2013
1 parent 071029f commit 4603487
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
13 changes: 6 additions & 7 deletions Lib/html/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
General functions for HTML manipulation.
"""


_escape_map = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;'}
_escape_map_full = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;',
ord('"'): '&quot;', ord('\''): '&#x27;'}

# NB: this is a candidate for a bytes/string polymorphic interface

def escape(s, quote=True):
Expand All @@ -16,6 +11,10 @@ def escape(s, quote=True):
characters, both double quote (") and single quote (') characters are also
translated.
"""
s = s.replace("&", "&amp;") # Must be done first!
s = s.replace("<", "&lt;")
s = s.replace(">", "&gt;")
if quote:
return s.translate(_escape_map_full)
return s.translate(_escape_map)
s = s.replace('"', "&quot;")
s = s.replace('\'', "&#x27;")
return s
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ Dave Brueck
Francisco Martín Brugué
Ian Bruntlett
Floris Bruynooghe
Matt Bryant
Stan Bubrouski
Erik de Bueger
Jan-Hein Bührman
Expand Down
3 changes: 3 additions & 0 deletions Misc/NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ Core and Builtins
Library
-------

- Issue #18020: improve html.escape speed by an order of magnitude.
Patch by Matt Bryant.

- Issue #18347: ElementTree's html serializer now preserves the case of
closing tags.

Expand Down

0 comments on commit 4603487

Please sign in to comment.