Skip to content

Commit

Permalink
implement missing str methods (#377)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism committed Jun 2, 2023
2 parents 60e7eb9 + c438e4d commit f3c78b1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ Version 2.1.3

Unreleased

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


Expand Down
10 changes: 10 additions & 0 deletions src/markupsafe/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import functools
import re
import string
import sys
import typing as t

if t.TYPE_CHECKING:
Expand Down Expand Up @@ -193,6 +194,11 @@ def escape(cls, s: t.Any) -> "Markup":
expandtabs = _simple_escaping_wrapper(str.expandtabs)
swapcase = _simple_escaping_wrapper(str.swapcase)
zfill = _simple_escaping_wrapper(str.zfill)
casefold = _simple_escaping_wrapper(str.casefold)

if sys.version_info >= (3, 9):
removeprefix = _simple_escaping_wrapper(str.removeprefix)
removesuffix = _simple_escaping_wrapper(str.removesuffix)

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

def format_map(self, map: t.Mapping[str, t.Any]) -> str: # type: ignore[override]
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, (), map))

def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
Expand Down
5 changes: 5 additions & 0 deletions tests/test_markupsafe.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ def test_format():
assert result == "<bar/>"


def test_format_map():
result = Markup("<em>{value}</em>").format_map({"value": "<value>"})
assert result == "<em>&lt;value&gt;</em>"


def test_formatting_empty():
formatted = Markup("{}").format(0)
assert formatted == Markup("0")
Expand Down

0 comments on commit f3c78b1

Please sign in to comment.