Skip to content

Commit 279aec6

Browse files
Modernize Python type hints and string formatting (#2012)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 7290f9c commit 279aec6

11 files changed

+33
-27
lines changed

debug_toolbar/_stubs.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from typing import Any, List, NamedTuple, Optional, Tuple
24

35
from django import template as dj_template

debug_toolbar/panels/profiling.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def func_std_string(self): # match what old profile produced
5959
# special case for built-in functions
6060
name = func_name[2]
6161
if name.startswith("<") and name.endswith(">"):
62-
return "{%s}" % name[1:-1]
62+
return f"{{{name[1:-1]}}}"
6363
else:
6464
return name
6565
else:

debug_toolbar/panels/sql/forms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def clean_alias(self):
4444
value = self.cleaned_data["alias"]
4545

4646
if value not in connections:
47-
raise ValidationError("Database alias '%s' not found" % value)
47+
raise ValidationError(f"Database alias '{value}' not found")
4848

4949
return value
5050

debug_toolbar/panels/versions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class VersionsPanel(Panel):
1616

1717
@property
1818
def nav_subtitle(self):
19-
return "Django %s" % django.get_version()
19+
return f"Django {django.get_version()}"
2020

2121
title = _("Versions")
2222

debug_toolbar/toolbar.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def debug_toolbar_urls(prefix="__debug__"):
218218
return []
219219
return [
220220
re_path(
221-
r"^%s/" % re.escape(prefix.lstrip("/")),
221+
r"^{}/".format(re.escape(prefix.lstrip("/"))),
222222
include("debug_toolbar.urls"),
223223
),
224224
]

debug_toolbar/utils.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
from __future__ import annotations
2+
13
import inspect
24
import linecache
35
import os.path
46
import sys
57
import warnings
68
from pprint import PrettyPrinter, pformat
7-
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
9+
from typing import Any, Sequence
810

911
from asgiref.local import Local
1012
from django.http import QueryDict
@@ -17,7 +19,7 @@
1719
_local_data = Local()
1820

1921

20-
def _is_excluded_frame(frame: Any, excluded_modules: Optional[Sequence[str]]) -> bool:
22+
def _is_excluded_frame(frame: Any, excluded_modules: Sequence[str] | None) -> bool:
2123
if not excluded_modules:
2224
return False
2325
frame_module = frame.f_globals.get("__name__")
@@ -39,7 +41,7 @@ def _stack_trace_deprecation_warning() -> None:
3941
)
4042

4143

42-
def tidy_stacktrace(stack: List[stubs.InspectStack]) -> stubs.TidyStackTrace:
44+
def tidy_stacktrace(stack: list[stubs.InspectStack]) -> stubs.TidyStackTrace:
4345
"""
4446
Clean up stacktrace and remove all entries that are excluded by the
4547
HIDE_IN_STACKTRACES setting.
@@ -99,7 +101,7 @@ def render_stacktrace(trace: stubs.TidyStackTrace) -> SafeString:
99101
return mark_safe(html)
100102

101103

102-
def get_template_info() -> Optional[Dict[str, Any]]:
104+
def get_template_info() -> dict[str, Any] | None:
103105
template_info = None
104106
cur_frame = sys._getframe().f_back
105107
try:
@@ -129,7 +131,7 @@ def get_template_info() -> Optional[Dict[str, Any]]:
129131

130132
def get_template_context(
131133
node: Node, context: stubs.RequestContext, context_lines: int = 3
132-
) -> Dict[str, Any]:
134+
) -> dict[str, Any]:
133135
line, source_lines, name = get_template_source_from_exception_info(node, context)
134136
debug_context = []
135137
start = max(1, line - context_lines)
@@ -146,7 +148,7 @@ def get_template_context(
146148

147149
def get_template_source_from_exception_info(
148150
node: Node, context: stubs.RequestContext
149-
) -> Tuple[int, List[Tuple[int, str]], str]:
151+
) -> tuple[int, list[tuple[int, str]], str]:
150152
if context.template.origin == node.origin:
151153
exception_info = context.template.get_exception_info(
152154
Exception("DDT"), node.token
@@ -213,8 +215,8 @@ def getframeinfo(frame: Any, context: int = 1) -> inspect.Traceback:
213215

214216

215217
def get_sorted_request_variable(
216-
variable: Union[Dict[str, Any], QueryDict],
217-
) -> Dict[str, Union[List[Tuple[str, Any]], Any]]:
218+
variable: dict[str, Any] | QueryDict,
219+
) -> dict[str, list[tuple[str, Any]] | Any]:
218220
"""
219221
Get a data structure for showing a sorted list of variables from the
220222
request data.
@@ -228,7 +230,7 @@ def get_sorted_request_variable(
228230
return {"raw": variable}
229231

230232

231-
def get_stack(context=1) -> List[stubs.InspectStack]:
233+
def get_stack(context=1) -> list[stubs.InspectStack]:
232234
"""
233235
Get a list of records for a frame and all higher (calling) frames.
234236
@@ -286,7 +288,7 @@ def get_source_file(self, frame):
286288
def get_stack_trace(
287289
self,
288290
*,
289-
excluded_modules: Optional[Sequence[str]] = None,
291+
excluded_modules: Sequence[str] | None = None,
290292
include_locals: bool = False,
291293
skip: int = 0,
292294
):

debug_toolbar/views.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def render_panel(request):
1818
"Data for this panel isn't available anymore. "
1919
"Please reload the page and retry."
2020
)
21-
content = "<p>%s</p>" % escape(content)
21+
content = f"<p>{escape(content)}</p>"
2222
scripts = []
2323
else:
2424
panel = toolbar.get_panel_by_id(request.GET["panel_id"])

tests/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,8 @@ def assertValidHTML(self, content):
107107
msg_parts = ["Invalid HTML:"]
108108
lines = content.split("\n")
109109
for position, errorcode, datavars in parser.errors:
110-
msg_parts.append(" %s" % html5lib.constants.E[errorcode] % datavars)
111-
msg_parts.append(" %s" % lines[position[0] - 1])
110+
msg_parts.append(f" {html5lib.constants.E[errorcode]}" % datavars)
111+
msg_parts.append(f" {lines[position[0] - 1]}")
112112
raise self.failureException("\n".join(msg_parts))
113113

114114

tests/test_csp_rendering.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from typing import Dict, cast
1+
from __future__ import annotations
2+
3+
from typing import cast
24
from xml.etree.ElementTree import Element
35

46
from django.conf import settings
@@ -12,7 +14,7 @@
1214
from .base import IntegrationTestCase
1315

1416

15-
def get_namespaces(element: Element) -> Dict[str, str]:
17+
def get_namespaces(element: Element) -> dict[str, str]:
1618
"""
1719
Return the default `xmlns`. See
1820
https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces
@@ -31,7 +33,7 @@ def setUp(self):
3133
self.parser = HTMLParser()
3234

3335
def _fail_if_missing(
34-
self, root: Element, path: str, namespaces: Dict[str, str], nonce: str
36+
self, root: Element, path: str, namespaces: dict[str, str], nonce: str
3537
):
3638
"""
3739
Search elements, fail if a `nonce` attribute is missing on them.
@@ -41,7 +43,7 @@ def _fail_if_missing(
4143
if item.attrib.get("nonce") != nonce:
4244
raise self.failureException(f"{item} has no nonce attribute.")
4345

44-
def _fail_if_found(self, root: Element, path: str, namespaces: Dict[str, str]):
46+
def _fail_if_found(self, root: Element, path: str, namespaces: dict[str, str]):
4547
"""
4648
Search elements, fail if a `nonce` attribute is found on them.
4749
"""
@@ -56,8 +58,8 @@ def _fail_on_invalid_html(self, content: bytes, parser: HTMLParser):
5658
default_msg = ["Content is invalid HTML:"]
5759
lines = content.split(b"\n")
5860
for position, error_code, data_vars in parser.errors:
59-
default_msg.append(" %s" % E[error_code] % data_vars)
60-
default_msg.append(" %r" % lines[position[0] - 1])
61+
default_msg.append(f" {E[error_code]}" % data_vars)
62+
default_msg.append(f" {lines[position[0] - 1]!r}")
6163
msg = self._formatMessage(None, "\n".join(default_msg))
6264
raise self.failureException(msg)
6365

tests/test_integration.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,8 @@ def test_html5_validation(self):
324324
default_msg = ["Content is invalid HTML:"]
325325
lines = content.split(b"\n")
326326
for position, errorcode, datavars in parser.errors:
327-
default_msg.append(" %s" % html5lib.constants.E[errorcode] % datavars)
328-
default_msg.append(" %r" % lines[position[0] - 1])
327+
default_msg.append(f" {html5lib.constants.E[errorcode]}" % datavars)
328+
default_msg.append(f" {lines[position[0] - 1]!r}")
329329
msg = self._formatMessage(None, "\n".join(default_msg))
330330
raise self.failureException(msg)
331331

tests/test_integration_async.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -247,8 +247,8 @@ async def test_html5_validation(self):
247247
default_msg = ["Content is invalid HTML:"]
248248
lines = content.split(b"\n")
249249
for position, errorcode, datavars in parser.errors:
250-
default_msg.append(" %s" % html5lib.constants.E[errorcode] % datavars)
251-
default_msg.append(" %r" % lines[position[0] - 1])
250+
default_msg.append(f" {html5lib.constants.E[errorcode]}" % datavars)
251+
default_msg.append(f" {lines[position[0] - 1]!r}")
252252
msg = self._formatMessage(None, "\n".join(default_msg))
253253
raise self.failureException(msg)
254254

0 commit comments

Comments
 (0)