Skip to content

Commit cc134bb

Browse files
authored
use Self for return type annotation (#379)
2 parents 5efbdb4 + 1e49fd5 commit cc134bb

2 files changed

Lines changed: 27 additions & 22 deletions

File tree

‎CHANGES.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Unreleased
66
- Implement ``format_map``, ``casefold``, ``removeprefix``, and ``removesuffix``
77
methods. :issue:`370`
88
- Fix static typing for basic ``str`` methods on ``Markup``. :issue:`358`
9+
- Use ``Self`` for annotating return types. :pr:`379`
910

1011

1112
Version 2.1.2

‎src/markupsafe/__init__.py‎

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ class Markup(str):
7070

7171
def __new__(
7272
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
73-
) -> "Markup":
73+
) -> "te.Self":
7474
if hasattr(base, "__html__"):
7575
base = base.__html__()
7676

@@ -79,30 +79,30 @@ def __new__(
7979

8080
return super().__new__(cls, base, encoding, errors)
8181

82-
def __html__(self) -> "Markup":
82+
def __html__(self) -> "te.Self":
8383
return self
8484

85-
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
85+
def __add__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
8686
if isinstance(other, str) or hasattr(other, "__html__"):
8787
return self.__class__(super().__add__(self.escape(other)))
8888

8989
return NotImplemented
9090

91-
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
91+
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "te.Self":
9292
if isinstance(other, str) or hasattr(other, "__html__"):
9393
return self.escape(other).__add__(self)
9494

9595
return NotImplemented
9696

97-
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
97+
def __mul__(self, num: "te.SupportsIndex") -> "te.Self":
9898
if isinstance(num, int):
9999
return self.__class__(super().__mul__(num))
100100

101101
return NotImplemented
102102

103103
__rmul__ = __mul__
104104

105-
def __mod__(self, arg: t.Any) -> "Markup":
105+
def __mod__(self, arg: t.Any) -> "te.Self":
106106
if isinstance(arg, tuple):
107107
# a tuple of arguments, each wrapped
108108
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
@@ -118,26 +118,28 @@ def __mod__(self, arg: t.Any) -> "Markup":
118118
def __repr__(self) -> str:
119119
return f"{self.__class__.__name__}({super().__repr__()})"
120120

121-
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
121+
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "te.Self":
122122
return self.__class__(super().join(map(self.escape, seq)))
123123

124124
join.__doc__ = str.join.__doc__
125125

126-
def split( # type: ignore
126+
def split( # type: ignore[override]
127127
self, sep: t.Optional[str] = None, maxsplit: int = -1
128-
) -> t.List["Markup"]:
128+
) -> t.List["te.Self"]:
129129
return [self.__class__(v) for v in super().split(sep, maxsplit)]
130130

131131
split.__doc__ = str.split.__doc__
132132

133-
def rsplit( # type: ignore
133+
def rsplit( # type: ignore[override]
134134
self, sep: t.Optional[str] = None, maxsplit: int = -1
135-
) -> t.List["Markup"]:
135+
) -> t.List["te.Self"]:
136136
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
137137

138138
rsplit.__doc__ = str.rsplit.__doc__
139139

140-
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
140+
def splitlines( # type: ignore[override]
141+
self, keepends: bool = False
142+
) -> t.List["te.Self"]:
141143
return [self.__class__(v) for v in super().splitlines(keepends)]
142144

143145
splitlines.__doc__ = str.splitlines.__doc__
@@ -164,10 +166,10 @@ def striptags(self) -> str:
164166
value = _strip_comments_re.sub("", self)
165167
value = _strip_tags_re.sub("", value)
166168
value = " ".join(value.split())
167-
return Markup(value).unescape()
169+
return self.__class__(value).unescape()
168170

169171
@classmethod
170-
def escape(cls, s: t.Any) -> "Markup":
172+
def escape(cls, s: t.Any) -> "te.Self":
171173
"""Escape a string. Calls :func:`escape` and ensures that for
172174
subclasses the correct type is returned.
173175
"""
@@ -176,7 +178,7 @@ def escape(cls, s: t.Any) -> "Markup":
176178
if rv.__class__ is not cls:
177179
return cls(rv)
178180

179-
return rv
181+
return rv # type: ignore[return-value]
180182

181183
__getitem__ = _simple_escaping_wrapper(str.__getitem__)
182184
capitalize = _simple_escaping_wrapper(str.capitalize)
@@ -200,25 +202,27 @@ def escape(cls, s: t.Any) -> "Markup":
200202
removeprefix = _simple_escaping_wrapper(str.removeprefix)
201203
removesuffix = _simple_escaping_wrapper(str.removesuffix)
202204

203-
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
205+
def partition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
204206
l, s, r = super().partition(self.escape(sep))
205207
cls = self.__class__
206208
return cls(l), cls(s), cls(r)
207209

208-
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
210+
def rpartition(self, sep: str) -> t.Tuple["te.Self", "te.Self", "te.Self"]:
209211
l, s, r = super().rpartition(self.escape(sep))
210212
cls = self.__class__
211213
return cls(l), cls(s), cls(r)
212214

213-
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
215+
def format(self, *args: t.Any, **kwargs: t.Any) -> "te.Self":
214216
formatter = EscapeFormatter(self.escape)
215217
return self.__class__(formatter.vformat(self, args, kwargs))
216218

217-
def format_map(self, map: t.Mapping[str, t.Any]) -> str: # type: ignore[override]
219+
def format_map( # type: ignore[override]
220+
self, map: t.Mapping[str, t.Any]
221+
) -> "te.Self":
218222
formatter = EscapeFormatter(self.escape)
219223
return self.__class__(formatter.vformat(self, (), map))
220224

221-
def __html_format__(self, format_spec: str) -> "Markup":
225+
def __html_format__(self, format_spec: str) -> "te.Self":
222226
if format_spec:
223227
raise ValueError("Unsupported format specification for Markup.")
224228

@@ -273,8 +277,8 @@ def __init__(self, obj: t.Any, escape: t.Callable[[t.Any], Markup]) -> None:
273277
self.obj = obj
274278
self.escape = escape
275279

276-
def __getitem__(self, item: t.Any) -> "_MarkupEscapeHelper":
277-
return _MarkupEscapeHelper(self.obj[item], self.escape)
280+
def __getitem__(self, item: t.Any) -> "te.Self":
281+
return self.__class__(self.obj[item], self.escape)
278282

279283
def __str__(self) -> str:
280284
return str(self.escape(self.obj))

0 commit comments

Comments
 (0)