Skip to content

Commit f3c78b1

Browse files
authored
implement missing str methods (#377)
2 parents 60e7eb9 + c438e4d commit f3c78b1

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

CHANGES.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ Version 2.1.3
33

44
Unreleased
55

6+
- Implement ``format_map``, ``casefold``, ``removeprefix``, and ``removesuffix``
7+
methods. :issue:`370`
68
- Fix static typing for basic ``str`` methods on ``Markup``. :issue:`358`
79

810

src/markupsafe/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import functools
22
import re
33
import string
4+
import sys
45
import typing as t
56

67
if t.TYPE_CHECKING:
@@ -193,6 +194,11 @@ def escape(cls, s: t.Any) -> "Markup":
193194
expandtabs = _simple_escaping_wrapper(str.expandtabs)
194195
swapcase = _simple_escaping_wrapper(str.swapcase)
195196
zfill = _simple_escaping_wrapper(str.zfill)
197+
casefold = _simple_escaping_wrapper(str.casefold)
198+
199+
if sys.version_info >= (3, 9):
200+
removeprefix = _simple_escaping_wrapper(str.removeprefix)
201+
removesuffix = _simple_escaping_wrapper(str.removesuffix)
196202

197203
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
198204
l, s, r = super().partition(self.escape(sep))
@@ -208,6 +214,10 @@ def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
208214
formatter = EscapeFormatter(self.escape)
209215
return self.__class__(formatter.vformat(self, args, kwargs))
210216

217+
def format_map(self, map: t.Mapping[str, t.Any]) -> str: # type: ignore[override]
218+
formatter = EscapeFormatter(self.escape)
219+
return self.__class__(formatter.vformat(self, (), map))
220+
211221
def __html_format__(self, format_spec: str) -> "Markup":
212222
if format_spec:
213223
raise ValueError("Unsupported format specification for Markup.")

tests/test_markupsafe.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,11 @@ def test_format():
108108
assert result == "<bar/>"
109109

110110

111+
def test_format_map():
112+
result = Markup("<em>{value}</em>").format_map({"value": "<value>"})
113+
assert result == "<em>&lt;value&gt;</em>"
114+
115+
111116
def test_formatting_empty():
112117
formatted = Markup("{}").format(0)
113118
assert formatted == Markup("0")

0 commit comments

Comments
 (0)