Skip to content

Commit 836a445

Browse files
authored
Merge pull request #566 from akx/modernize-f-strings
Replace string interpolation and .format calls with f-strings
2 parents b8a9b11 + 9a8daee commit 836a445

File tree

17 files changed

+96
-112
lines changed

17 files changed

+96
-112
lines changed

example/pexp/management/commands/p2cmd.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ def wrapper(*arg):
3535
for r in results:
3636
res_sum += r
3737
print(
38-
"%s%-19s: %.4f ms, %i queries (%i times)"
39-
% (message, func.func_name, res_sum, len(connection.queries), iterations)
38+
f"{message}{func.func_name:<19}: {res_sum:.4f} ms, "
39+
f"{len(connection.queries)} queries ({iterations} times)"
4040
)
4141
sys.stdout.flush()
4242

@@ -106,13 +106,12 @@ def poly_sql_query():
106106
def poly_sql_query2():
107107
cursor = connection.cursor()
108108
cursor.execute(
109-
"""
109+
f"""
110110
SELECT id, pexp_testmodela.field1
111111
FROM pexp_testmodela
112-
WHERE pexp_testmodela.field1=%i
112+
WHERE pexp_testmodela.field1={rnd.randint(0, 100)}
113113
ORDER BY pexp_testmodela.id
114114
"""
115-
% rnd.randint(0, 100)
116115
)
117116
# row=cursor.fetchone()
118117
return

example/pexp/management/commands/polybench.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ def wrapper(*arg):
3939
res_sum += r
4040
median = res_sum / len(results)
4141
print(
42-
"%s%-19s: %.0f ms, %i queries"
43-
% (message, func.func_name, median, len(connection.queries) / len(results))
42+
f"{message}{func.func_name:<19}: {median:.0f} ms, "
43+
f"{len(connection.queries) / len(results):d} queries"
4444
)
4545
sys.stdout.flush()
4646

@@ -61,7 +61,9 @@ def run_vanilla_any_poly(func, iterations=1):
6161
def bench_create(model):
6262
for i in range(num_objects):
6363
model.objects.create(
64-
field1="abc" + str(i), field2="abcd" + str(i), field3="abcde" + str(i)
64+
field1=f"abc{i}",
65+
field2=f"abcd{i}",
66+
field3=f"abcde{i}",
6567
)
6668
# print 'count:',model.objects.count()
6769

polymorphic/admin/childadmin.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,10 @@ def change_form_template(self):
9090

9191
return [
9292
f"admin/{app_label}/{opts.object_name.lower()}/change_form.html",
93-
"admin/%s/change_form.html" % app_label,
93+
f"admin/{app_label}/change_form.html",
9494
# Added:
95-
"admin/%s/%s/change_form.html" % (base_app_label, base_opts.object_name.lower()),
96-
"admin/%s/change_form.html" % base_app_label,
95+
f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_form.html",
96+
f"admin/{base_app_label}/change_form.html",
9797
"admin/polymorphic/change_form.html",
9898
"admin/change_form.html",
9999
]
@@ -108,12 +108,11 @@ def delete_confirmation_template(self):
108108
base_app_label = base_opts.app_label
109109

110110
return [
111-
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
112-
"admin/%s/delete_confirmation.html" % app_label,
111+
f"admin/{app_label}/{opts.object_name.lower()}/delete_confirmation.html",
112+
f"admin/{app_label}/delete_confirmation.html",
113113
# Added:
114-
"admin/%s/%s/delete_confirmation.html"
115-
% (base_app_label, base_opts.object_name.lower()),
116-
"admin/%s/delete_confirmation.html" % base_app_label,
114+
f"admin/{base_app_label}/{base_opts.object_name.lower()}/delete_confirmation.html",
115+
f"admin/{base_app_label}/delete_confirmation.html",
117116
"admin/polymorphic/delete_confirmation.html",
118117
"admin/delete_confirmation.html",
119118
]
@@ -129,10 +128,10 @@ def object_history_template(self):
129128

130129
return [
131130
f"admin/{app_label}/{opts.object_name.lower()}/object_history.html",
132-
"admin/%s/object_history.html" % app_label,
131+
f"admin/{app_label}/object_history.html",
133132
# Added:
134-
"admin/%s/%s/object_history.html" % (base_app_label, base_opts.object_name.lower()),
135-
"admin/%s/object_history.html" % base_app_label,
133+
f"admin/{base_app_label}/{base_opts.object_name.lower()}/object_history.html",
134+
f"admin/{base_app_label}/object_history.html",
136135
"admin/polymorphic/object_history.html",
137136
"admin/object_history.html",
138137
]

polymorphic/admin/filters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,6 @@ def queryset(self, request, queryset):
3232
if choice_value == value:
3333
return queryset.filter(polymorphic_ctype_id=choice_value)
3434
raise PermissionDenied(
35-
'Invalid ContentType "{}". It must be registered as child model.'.format(value)
35+
f'Invalid ContentType "{value}". It must be registered as child model.'
3636
)
3737
return queryset

polymorphic/admin/helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def inline_formset_data(self):
9191
verbose_name = self.opts.verbose_name
9292
return json.dumps(
9393
{
94-
"name": "#%s" % self.formset.prefix,
94+
"name": f"#{self.formset.prefix}",
9595
"options": {
9696
"prefix": self.formset.prefix,
9797
"addText": gettext("Add another %(verbose_name)s")

polymorphic/admin/inlines.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin):
3838
#: This can be redefined for subclasses.
3939
polymorphic_media = Media(
4040
js=(
41-
"admin/js/vendor/jquery/jquery{}.js".format("" if settings.DEBUG else ".min"),
41+
f"admin/js/vendor/jquery/{'jquery' if settings.DEBUG else 'jquery.min'}.js",
4242
"admin/js/jquery.init.js",
4343
"polymorphic/js/polymorphic_inlines.js",
4444
),

polymorphic/admin/parentadmin.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -97,14 +97,10 @@ def register_child(self, model, model_admin):
9797
raise RegistrationClosed("The admin model can't be registered anymore at this point.")
9898

9999
if not issubclass(model, self.base_model):
100-
raise TypeError(
101-
"{} should be a subclass of {}".format(model.__name__, self.base_model.__name__)
102-
)
100+
raise TypeError(f"{model.__name__} should be a subclass of {self.base_model.__name__}")
103101
if not issubclass(model_admin, admin.ModelAdmin):
104102
raise TypeError(
105-
"{} should be a subclass of {}".format(
106-
model_admin.__name__, admin.ModelAdmin.__name__
107-
)
103+
f"{model_admin.__name__} should be a subclass of {admin.ModelAdmin.__name__}"
108104
)
109105

110106
self._child_admin_site.register(model, model_admin)
@@ -159,7 +155,8 @@ def _get_real_admin_by_ct(self, ct_id, super_if_self=True):
159155
model_class = ct.model_class()
160156
if not model_class:
161157
# Handle model deletion
162-
raise Http404("No model found for '{}.{}'.".format(*ct.natural_key()))
158+
app_label, model = ct.natural_key()
159+
raise Http404(f"No model found for '{app_label}.{model}'.")
163160

164161
return self._get_real_admin_by_model(model_class, super_if_self=super_if_self)
165162

@@ -168,7 +165,7 @@ def _get_real_admin_by_model(self, model_class, super_if_self=True):
168165
# Hence, make sure this is a derived object, or risk exposing other admin interfaces.
169166
if model_class not in self._child_models:
170167
raise PermissionDenied(
171-
"Invalid model '{}', it must be registered as child model.".format(model_class)
168+
f"Invalid model '{model_class}', it must be registered as child model."
172169
)
173170

174171
try:
@@ -177,7 +174,7 @@ def _get_real_admin_by_model(self, model_class, super_if_self=True):
177174
real_admin = self._child_admin_site._registry[model_class]
178175
except KeyError:
179176
raise ChildAdminNotRegistered(
180-
"No child admin site was registered for a '{}' model.".format(model_class)
177+
f"No child admin site was registered for a '{model_class}' model."
181178
)
182179

183180
if super_if_self and real_admin is self:
@@ -273,7 +270,7 @@ def subclass_view(self, request, path):
273270
object_id = int(path[0:pos])
274271
except ValueError:
275272
raise Http404(
276-
"No ct_id parameter, unable to find admin subclass for path '{}'.".format(path)
273+
f"No ct_id parameter, unable to find admin subclass for path '{path}'."
277274
)
278275

279276
ct_id = self.model.objects.values_list("polymorphic_ctype_id", flat=True).get(
@@ -299,7 +296,8 @@ def add_type_view(self, request, form_url=""):
299296
if request.META["QUERY_STRING"]:
300297
# QUERY_STRING is bytes in Python 3, using force_str() to decode it as string.
301298
# See QueryDict how Django deals with that.
302-
extra_qs = "&{}".format(force_str(request.META["QUERY_STRING"]))
299+
# TODO: should this use a Django method instead of manipulating the string directly?
300+
extra_qs = f"&{force_str(request.META['QUERY_STRING'])}"
303301

304302
choices = self.get_child_type_choices(request, "add")
305303
if len(choices) == 0:
@@ -315,7 +313,7 @@ def add_type_view(self, request, form_url=""):
315313
form.fields["ct_id"].choices = choices
316314

317315
if form.is_valid():
318-
return HttpResponseRedirect("?ct_id={}{}".format(form.cleaned_data["ct_id"], extra_qs))
316+
return HttpResponseRedirect(f"?ct_id={form.cleaned_data['ct_id']}{extra_qs}")
319317

320318
# Wrap in all admin layout
321319
fieldsets = ((None, {"fields": ("ct_id",)}),)
@@ -351,7 +349,7 @@ def render_add_type_form(self, request, context, form_url=""):
351349

352350
templates = self.add_type_template or [
353351
f"admin/{app_label}/{opts.object_name.lower()}/add_type_form.html",
354-
"admin/%s/add_type_form.html" % app_label,
352+
f"admin/{app_label}/add_type_form.html",
355353
"admin/polymorphic/add_type_form.html", # added default here
356354
"admin/add_type_form.html",
357355
]
@@ -370,9 +368,9 @@ def change_list_template(self):
370368

371369
return [
372370
f"admin/{app_label}/{opts.object_name.lower()}/change_list.html",
373-
"admin/%s/change_list.html" % app_label,
371+
f"admin/{app_label}/change_list.html",
374372
# Added base class:
375-
"admin/%s/%s/change_list.html" % (base_app_label, base_opts.object_name.lower()),
376-
"admin/%s/change_list.html" % base_app_label,
373+
f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_list.html",
374+
f"admin/{base_app_label}/change_list.html",
377375
"admin/change_list.html",
378376
]

polymorphic/base.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,10 @@ def validate_model_fields(self, new_class):
119119
"check if all fields names are allowed (i.e. not in POLYMORPHIC_SPECIAL_Q_KWORDS)"
120120
for f in new_class._meta.fields:
121121
if f.name in POLYMORPHIC_SPECIAL_Q_KWORDS:
122-
e = 'PolymorphicModel: "%s" - field name "%s" is not allowed in polymorphic models'
123-
raise AssertionError(e % (new_class.__name__, f.name))
122+
raise AssertionError(
123+
f'PolymorphicModel: "{new_class.__name__}" - '
124+
f'field name "{f.name}" is not allowed in polymorphic models'
125+
)
124126

125127
@classmethod
126128
def validate_model_manager(self, manager, model_name, manager_name):
@@ -133,10 +135,8 @@ def validate_model_manager(self, manager, model_name, manager_name):
133135
else:
134136
extra = ""
135137
e = (
136-
'PolymorphicModel: "{0}.{1}" manager is of type "{2}", but must be a subclass of'
137-
" PolymorphicManager.{extra} to support retrieving subclasses".format(
138-
model_name, manager_name, type(manager).__name__, extra=extra
139-
)
138+
f'PolymorphicModel: "{model_name}.{manager_name}" manager is of type "{type(manager).__name__}", '
139+
f"but must be a subclass of PolymorphicManager.{extra} to support retrieving subclasses"
140140
)
141141
warnings.warn(e, ManagerInheritanceWarning, stacklevel=3)
142142
return manager
@@ -145,10 +145,8 @@ def validate_model_manager(self, manager, model_name, manager_name):
145145
manager.queryset_class, PolymorphicQuerySet
146146
):
147147
e = (
148-
'PolymorphicModel: "{}.{}" has been instantiated with a queryset class '
149-
"which is not a subclass of PolymorphicQuerySet (which is required)".format(
150-
model_name, manager_name
151-
)
148+
f'PolymorphicModel: "{model_name}.{manager_name}" has been instantiated with a queryset class '
149+
f"which is not a subclass of PolymorphicQuerySet (which is required)"
152150
)
153151
warnings.warn(e, ManagerInheritanceWarning, stacklevel=3)
154152
return manager
@@ -157,7 +155,7 @@ def validate_model_manager(self, manager, model_name, manager_name):
157155
def base_objects(self):
158156
warnings.warn(
159157
"Using PolymorphicModel.base_objects is deprecated.\n"
160-
"Use {}.objects.non_polymorphic() instead.".format(self.__class__.__name__),
158+
f"Use {self.__class__.__name__}.objects.non_polymorphic() instead.",
161159
DeprecationWarning,
162160
stacklevel=2,
163161
)
@@ -193,7 +191,7 @@ def _default_manager(self):
193191
manager = super()._default_manager
194192
if not isinstance(manager, PolymorphicManager):
195193
warnings.warn(
196-
"{}._default_manager is not a PolymorphicManager".format(self.__class__.__name__),
194+
f"{self.__class__.__name__}._default_manager is not a PolymorphicManager",
197195
ManagerInheritanceWarning,
198196
)
199197

polymorphic/formsets/generic.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def get_form(self, ct_field="content_type", fk_field="object_id", **kwargs):
4242
not isinstance(ct_field, models.ForeignKey)
4343
or ct_field.remote_field.model != ContentType
4444
):
45-
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
45+
raise Exception(f"fk_name '{ct_field}' is not a ForeignKey to ContentType")
4646

4747
fk_field = opts.get_field(self.fk_field) # let the exception propagate
4848
exclude.extend([ct_field.name, fk_field.name])

polymorphic/formsets/models.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ def _construct_form(self, i, **kwargs):
188188
ct_id = int(self.data[f"{prefix}-polymorphic_ctype"])
189189
except (KeyError, ValueError):
190190
raise ValidationError(
191-
"Formset row {} has no 'polymorphic_ctype' defined!".format(prefix)
191+
f"Formset row {prefix} has no 'polymorphic_ctype' defined!"
192192
)
193193

194194
model = ContentType.objects.get_for_id(ct_id).model_class()
@@ -243,10 +243,8 @@ def get_form_class(self, model):
243243
except KeyError:
244244
# This may happen when the query returns objects of a type that was not handled by the formset.
245245
raise UnsupportedChildType(
246-
"The '{}' found a '{}' model in the queryset, "
247-
"but no form class is registered to display it.".format(
248-
self.__class__.__name__, model.__name__
249-
)
246+
f"The '{self.__class__.__name__}' found a '{model.__name__}' model in the queryset, "
247+
f"but no form class is registered to display it."
250248
)
251249

252250
def is_multipart(self):

0 commit comments

Comments
 (0)