Skip to content

Add pyupgrade and django-upgrade pre-commit hooks #1553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ repos:
rev: 0.10.1
hooks:
- id: doc8
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.1
hooks:
- id: pyupgrade
args: [--py36-plus]
- repo: https://github.com/adamchainz/django-upgrade
rev: 1.4.0
hooks:
- id: django-upgrade
args: [--target-version, "3.2"]
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
Expand Down
2 changes: 1 addition & 1 deletion debug_toolbar/management/commands/debugsqlshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def execute(self, sql, params=()):
end_time = time()
duration = (end_time - start_time) * 1000
formatted_sql = sqlparse.format(raw_sql, reindent=True)
print("{} [{:.2f}ms]".format(formatted_sql, duration))
print(f"{formatted_sql} [{duration:.2f}ms]")


base_module.CursorDebugWrapper = PrintQueryWrapper
2 changes: 1 addition & 1 deletion debug_toolbar/panels/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(self, cache):
self.cache = cache

def __repr__(self):
return str("<CacheStatTracker for %s>") % repr(self.cache)
return "<CacheStatTracker for %s>" % repr(self.cache)

def _get_func_info(self):
frame = sys._getframe(3)
Expand Down
2 changes: 1 addition & 1 deletion debug_toolbar/panels/profiling.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def parent_classes(self):

def background(self):
r, g, b = hsv_to_rgb(*self.hsv)
return "rgb({:f}%,{:f}%,{:f}%)".format(r * 100, g * 100, b * 100)
return f"rgb({r * 100:f}%,{g * 100:f}%,{b * 100:f}%)"

def func_std_string(self): # match what old profile produced
func_name = self.func
Expand Down
2 changes: 1 addition & 1 deletion debug_toolbar/panels/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def generate_stats(self, request, response):
receiver_class_name = getattr(
receiver.__self__, "__class__", type
).__name__
text = "{}.{}".format(receiver_class_name, receiver_name)
text = f"{receiver_class_name}.{receiver_name}"
else:
text = receiver_name
receivers.append(text)
Expand Down
4 changes: 2 additions & 2 deletions debug_toolbar/panels/sql/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def reformat_sql(sql, with_toggle=False):
if not with_toggle:
return formatted
simple = simplify(parse_sql(sql, aligned_indent=False))
uncollapsed = '<span class="djDebugUncollapsed">{}</span>'.format(simple)
collapsed = '<span class="djDebugCollapsed djdt-hidden">{}</span>'.format(formatted)
uncollapsed = f'<span class="djDebugUncollapsed">{simple}</span>'
collapsed = f'<span class="djDebugCollapsed djdt-hidden">{formatted}</span>'
return collapsed + uncollapsed


Expand Down
6 changes: 3 additions & 3 deletions debug_toolbar/panels/sql/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ def sql_explain(request, verified_data):
# SQLite's EXPLAIN dumps the low-level opcodes generated for a query;
# EXPLAIN QUERY PLAN dumps a more human-readable summary
# See https://www.sqlite.org/lang_explain.html for details
cursor.execute("EXPLAIN QUERY PLAN {}".format(sql), params)
cursor.execute(f"EXPLAIN QUERY PLAN {sql}", params)
elif vendor == "postgresql":
cursor.execute("EXPLAIN ANALYZE {}".format(sql), params)
cursor.execute(f"EXPLAIN ANALYZE {sql}", params)
else:
cursor.execute("EXPLAIN {}".format(sql), params)
cursor.execute(f"EXPLAIN {sql}", params)
headers = [d[0] for d in cursor.description]
result = cursor.fetchall()

Expand Down
2 changes: 1 addition & 1 deletion debug_toolbar/panels/templates/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def _request_context_bind_template(self, template):
self.context_processors = OrderedDict()
updates = {}
for processor in processors:
name = "{}.{}".format(processor.__module__, processor.__name__)
name = f"{processor.__module__}.{processor.__name__}"
context = processor(self.request)
self.context_processors[name] = context
updates.update(context)
Expand Down
2 changes: 1 addition & 1 deletion debug_toolbar/panels/templates/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def template_source(request):
except TemplateDoesNotExist:
pass
else:
source = "Template Does Not Exist: {}".format(template_origin_name)
source = f"Template Does Not Exist: {template_origin_name}"

try:
from pygments import highlight
Expand Down
4 changes: 2 additions & 2 deletions debug_toolbar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def get_module_path(module_name):
try:
module = import_module(module_name)
except ImportError as e:
raise ImproperlyConfigured("Error importing HIDE_IN_STACKTRACES: {}".format(e))
raise ImproperlyConfigured(f"Error importing HIDE_IN_STACKTRACES: {e}")
else:
source_path = inspect.getsourcefile(module)
if source_path.endswith("__init__.py"):
Expand Down Expand Up @@ -157,7 +157,7 @@ def get_name_from_obj(obj):

if hasattr(obj, "__module__"):
module = obj.__module__
name = "{}.{}".format(module, name)
name = f"{module}.{name}"

return name

Expand Down
12 changes: 6 additions & 6 deletions tests/panels/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,12 @@ def test_param_conversion(self):
# comparisons in MySQL.
if not (django.VERSION >= (4, 1) and connection.vendor == "mysql"):
self.assertEqual(
tuple([q[1]["params"] for q in self.panel._queries]),
tuple(q[1]["params"] for q in self.panel._queries),
('["Foo"]', "[10, 1]", '["2017-12-22 16:07:01"]'),
)
else:
self.assertEqual(
tuple([q[1]["params"] for q in self.panel._queries]),
tuple(q[1]["params"] for q in self.panel._queries),
('["Foo", true, false]', "[10, 1]", '["2017-12-22 16:07:01"]'),
)

Expand Down Expand Up @@ -227,7 +227,7 @@ def test_raw_query_param_conversion(self):
self.assertEqual(len(self.panel._queries), 2)

self.assertEqual(
tuple([q[1]["params"] for q in self.panel._queries]),
tuple(q[1]["params"] for q in self.panel._queries),
(
'["Foo", true, false, "2017-12-22 16:07:01"]',
" ".join(
Expand All @@ -246,7 +246,7 @@ def test_insert_content(self):
Test that the panel only inserts content after generate_stats and
not the process_request.
"""
list(User.objects.filter(username="café".encode("utf-8")))
list(User.objects.filter(username="café".encode()))
response = self.panel.process_request(self.request)
# ensure the panel does not have content yet.
self.assertNotIn("café", self.panel.content)
Expand All @@ -262,7 +262,7 @@ def test_insert_locals(self):
Test that the panel inserts locals() content.
"""
local_var = "<script>alert('test');</script>" # noqa: F841
list(User.objects.filter(username="café".encode("utf-8")))
list(User.objects.filter(username="café".encode()))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.assertIn("local_var", self.panel.content)
Expand All @@ -276,7 +276,7 @@ def test_not_insert_locals(self):
"""
Test that the panel does not insert locals() content.
"""
list(User.objects.filter(username="café".encode("utf-8")))
list(User.objects.filter(username="café".encode()))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.assertNotIn("djdt-locals", self.panel.content)
Expand Down