Skip to content

Commit

Permalink
Merge pull request #566 from akx/modernize-f-strings
Browse files Browse the repository at this point in the history
Replace string interpolation and .format calls with f-strings
  • Loading branch information
j-antunes authored Dec 30, 2023
2 parents b8a9b11 + 9a8daee commit 836a445
Show file tree
Hide file tree
Showing 17 changed files with 96 additions and 112 deletions.
9 changes: 4 additions & 5 deletions example/pexp/management/commands/p2cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ def wrapper(*arg):
for r in results:
res_sum += r
print(
"%s%-19s: %.4f ms, %i queries (%i times)"
% (message, func.func_name, res_sum, len(connection.queries), iterations)
f"{message}{func.func_name:<19}: {res_sum:.4f} ms, "
f"{len(connection.queries)} queries ({iterations} times)"
)
sys.stdout.flush()

Expand Down Expand Up @@ -106,13 +106,12 @@ def poly_sql_query():
def poly_sql_query2():
cursor = connection.cursor()
cursor.execute(
"""
f"""
SELECT id, pexp_testmodela.field1
FROM pexp_testmodela
WHERE pexp_testmodela.field1=%i
WHERE pexp_testmodela.field1={rnd.randint(0, 100)}
ORDER BY pexp_testmodela.id
"""
% rnd.randint(0, 100)
)
# row=cursor.fetchone()
return
8 changes: 5 additions & 3 deletions example/pexp/management/commands/polybench.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ def wrapper(*arg):
res_sum += r
median = res_sum / len(results)
print(
"%s%-19s: %.0f ms, %i queries"
% (message, func.func_name, median, len(connection.queries) / len(results))
f"{message}{func.func_name:<19}: {median:.0f} ms, "
f"{len(connection.queries) / len(results):d} queries"
)
sys.stdout.flush()

Expand All @@ -61,7 +61,9 @@ def run_vanilla_any_poly(func, iterations=1):
def bench_create(model):
for i in range(num_objects):
model.objects.create(
field1="abc" + str(i), field2="abcd" + str(i), field3="abcde" + str(i)
field1=f"abc{i}",
field2=f"abcd{i}",
field3=f"abcde{i}",
)
# print 'count:',model.objects.count()

Expand Down
21 changes: 10 additions & 11 deletions polymorphic/admin/childadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ def change_form_template(self):

return [
f"admin/{app_label}/{opts.object_name.lower()}/change_form.html",
"admin/%s/change_form.html" % app_label,
f"admin/{app_label}/change_form.html",
# Added:
"admin/%s/%s/change_form.html" % (base_app_label, base_opts.object_name.lower()),
"admin/%s/change_form.html" % base_app_label,
f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_form.html",
f"admin/{base_app_label}/change_form.html",
"admin/polymorphic/change_form.html",
"admin/change_form.html",
]
Expand All @@ -108,12 +108,11 @@ def delete_confirmation_template(self):
base_app_label = base_opts.app_label

return [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
f"admin/{app_label}/{opts.object_name.lower()}/delete_confirmation.html",
f"admin/{app_label}/delete_confirmation.html",
# Added:
"admin/%s/%s/delete_confirmation.html"
% (base_app_label, base_opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % base_app_label,
f"admin/{base_app_label}/{base_opts.object_name.lower()}/delete_confirmation.html",
f"admin/{base_app_label}/delete_confirmation.html",
"admin/polymorphic/delete_confirmation.html",
"admin/delete_confirmation.html",
]
Expand All @@ -129,10 +128,10 @@ def object_history_template(self):

return [
f"admin/{app_label}/{opts.object_name.lower()}/object_history.html",
"admin/%s/object_history.html" % app_label,
f"admin/{app_label}/object_history.html",
# Added:
"admin/%s/%s/object_history.html" % (base_app_label, base_opts.object_name.lower()),
"admin/%s/object_history.html" % base_app_label,
f"admin/{base_app_label}/{base_opts.object_name.lower()}/object_history.html",
f"admin/{base_app_label}/object_history.html",
"admin/polymorphic/object_history.html",
"admin/object_history.html",
]
Expand Down
2 changes: 1 addition & 1 deletion polymorphic/admin/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ def queryset(self, request, queryset):
if choice_value == value:
return queryset.filter(polymorphic_ctype_id=choice_value)
raise PermissionDenied(
'Invalid ContentType "{}". It must be registered as child model.'.format(value)
f'Invalid ContentType "{value}". It must be registered as child model.'
)
return queryset
2 changes: 1 addition & 1 deletion polymorphic/admin/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def inline_formset_data(self):
verbose_name = self.opts.verbose_name
return json.dumps(
{
"name": "#%s" % self.formset.prefix,
"name": f"#{self.formset.prefix}",
"options": {
"prefix": self.formset.prefix,
"addText": gettext("Add another %(verbose_name)s")
Expand Down
2 changes: 1 addition & 1 deletion polymorphic/admin/inlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin):
#: This can be redefined for subclasses.
polymorphic_media = Media(
js=(
"admin/js/vendor/jquery/jquery{}.js".format("" if settings.DEBUG else ".min"),
f"admin/js/vendor/jquery/{'jquery' if settings.DEBUG else 'jquery.min'}.js",
"admin/js/jquery.init.js",
"polymorphic/js/polymorphic_inlines.js",
),
Expand Down
30 changes: 14 additions & 16 deletions polymorphic/admin/parentadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,10 @@ def register_child(self, model, model_admin):
raise RegistrationClosed("The admin model can't be registered anymore at this point.")

if not issubclass(model, self.base_model):
raise TypeError(
"{} should be a subclass of {}".format(model.__name__, self.base_model.__name__)
)
raise TypeError(f"{model.__name__} should be a subclass of {self.base_model.__name__}")
if not issubclass(model_admin, admin.ModelAdmin):
raise TypeError(
"{} should be a subclass of {}".format(
model_admin.__name__, admin.ModelAdmin.__name__
)
f"{model_admin.__name__} should be a subclass of {admin.ModelAdmin.__name__}"
)

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

return self._get_real_admin_by_model(model_class, super_if_self=super_if_self)

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

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

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

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

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

if form.is_valid():
return HttpResponseRedirect("?ct_id={}{}".format(form.cleaned_data["ct_id"], extra_qs))
return HttpResponseRedirect(f"?ct_id={form.cleaned_data['ct_id']}{extra_qs}")

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

templates = self.add_type_template or [
f"admin/{app_label}/{opts.object_name.lower()}/add_type_form.html",
"admin/%s/add_type_form.html" % app_label,
f"admin/{app_label}/add_type_form.html",
"admin/polymorphic/add_type_form.html", # added default here
"admin/add_type_form.html",
]
Expand All @@ -370,9 +368,9 @@ def change_list_template(self):

return [
f"admin/{app_label}/{opts.object_name.lower()}/change_list.html",
"admin/%s/change_list.html" % app_label,
f"admin/{app_label}/change_list.html",
# Added base class:
"admin/%s/%s/change_list.html" % (base_app_label, base_opts.object_name.lower()),
"admin/%s/change_list.html" % base_app_label,
f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_list.html",
f"admin/{base_app_label}/change_list.html",
"admin/change_list.html",
]
22 changes: 10 additions & 12 deletions polymorphic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,10 @@ def validate_model_fields(self, new_class):
"check if all fields names are allowed (i.e. not in POLYMORPHIC_SPECIAL_Q_KWORDS)"
for f in new_class._meta.fields:
if f.name in POLYMORPHIC_SPECIAL_Q_KWORDS:
e = 'PolymorphicModel: "%s" - field name "%s" is not allowed in polymorphic models'
raise AssertionError(e % (new_class.__name__, f.name))
raise AssertionError(
f'PolymorphicModel: "{new_class.__name__}" - '
f'field name "{f.name}" is not allowed in polymorphic models'
)

@classmethod
def validate_model_manager(self, manager, model_name, manager_name):
Expand All @@ -133,10 +135,8 @@ def validate_model_manager(self, manager, model_name, manager_name):
else:
extra = ""
e = (
'PolymorphicModel: "{0}.{1}" manager is of type "{2}", but must be a subclass of'
" PolymorphicManager.{extra} to support retrieving subclasses".format(
model_name, manager_name, type(manager).__name__, extra=extra
)
f'PolymorphicModel: "{model_name}.{manager_name}" manager is of type "{type(manager).__name__}", '
f"but must be a subclass of PolymorphicManager.{extra} to support retrieving subclasses"
)
warnings.warn(e, ManagerInheritanceWarning, stacklevel=3)
return manager
Expand All @@ -145,10 +145,8 @@ def validate_model_manager(self, manager, model_name, manager_name):
manager.queryset_class, PolymorphicQuerySet
):
e = (
'PolymorphicModel: "{}.{}" has been instantiated with a queryset class '
"which is not a subclass of PolymorphicQuerySet (which is required)".format(
model_name, manager_name
)
f'PolymorphicModel: "{model_name}.{manager_name}" has been instantiated with a queryset class '
f"which is not a subclass of PolymorphicQuerySet (which is required)"
)
warnings.warn(e, ManagerInheritanceWarning, stacklevel=3)
return manager
Expand All @@ -157,7 +155,7 @@ def validate_model_manager(self, manager, model_name, manager_name):
def base_objects(self):
warnings.warn(
"Using PolymorphicModel.base_objects is deprecated.\n"
"Use {}.objects.non_polymorphic() instead.".format(self.__class__.__name__),
f"Use {self.__class__.__name__}.objects.non_polymorphic() instead.",
DeprecationWarning,
stacklevel=2,
)
Expand Down Expand Up @@ -193,7 +191,7 @@ def _default_manager(self):
manager = super()._default_manager
if not isinstance(manager, PolymorphicManager):
warnings.warn(
"{}._default_manager is not a PolymorphicManager".format(self.__class__.__name__),
f"{self.__class__.__name__}._default_manager is not a PolymorphicManager",
ManagerInheritanceWarning,
)

Expand Down
2 changes: 1 addition & 1 deletion polymorphic/formsets/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def get_form(self, ct_field="content_type", fk_field="object_id", **kwargs):
not isinstance(ct_field, models.ForeignKey)
or ct_field.remote_field.model != ContentType
):
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
raise Exception(f"fk_name '{ct_field}' is not a ForeignKey to ContentType")

fk_field = opts.get_field(self.fk_field) # let the exception propagate
exclude.extend([ct_field.name, fk_field.name])
Expand Down
8 changes: 3 additions & 5 deletions polymorphic/formsets/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def _construct_form(self, i, **kwargs):
ct_id = int(self.data[f"{prefix}-polymorphic_ctype"])
except (KeyError, ValueError):
raise ValidationError(
"Formset row {} has no 'polymorphic_ctype' defined!".format(prefix)
f"Formset row {prefix} has no 'polymorphic_ctype' defined!"
)

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

def is_multipart(self):
Expand Down
5 changes: 2 additions & 3 deletions polymorphic/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ def get_queryset(self):
return qs

def __str__(self):
return "{} (PolymorphicManager) using {}".format(
self.__class__.__name__,
self.queryset_class.__name__,
return (
f"{self.__class__.__name__} (PolymorphicManager) using {self.queryset_class.__name__}"
)

# Proxied methods
Expand Down
12 changes: 4 additions & 8 deletions polymorphic/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,9 @@ def get_real_instance_class(self):
"""
if self.polymorphic_ctype_id is None:
raise PolymorphicTypeUndefined(
(
"The model {}#{} does not have a `polymorphic_ctype_id` value defined.\n"
"If you created models outside polymorphic, e.g. through an import or migration, "
"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
).format(self.__class__.__name__, self.pk)
f"The model {self.__class__.__name__}#{self.pk} does not have a `polymorphic_ctype_id` value defined.\n"
f"If you created models outside polymorphic, e.g. through an import or migration, "
f"make sure the `polymorphic_ctype_id` field points to the ContentType ID of the model subclass."
)

# the following line would be the easiest way to do this, but it produces sql queries
Expand All @@ -127,9 +125,7 @@ def get_real_instance_class(self):
)
):
raise PolymorphicTypeInvalid(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
f"ContentType {self.polymorphic_ctype_id} for {model} #{self.pk} does not point to a subclass!"
)

return model
Expand Down
10 changes: 5 additions & 5 deletions polymorphic/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ class self.model, but as a class derived from self.model. We want to re-fetch
for real_concrete_class, idlist in idlist_per_model.items():
indices = indexlist_per_model[real_concrete_class]
real_objects = real_concrete_class._base_objects.db_manager(self.db).filter(
**{("%s__in" % pk_name): idlist}
**{(f"{pk_name}__in"): idlist}
)
# copy select related configuration to new qs
real_objects.query.select_related = self.query.select_related
Expand Down Expand Up @@ -504,15 +504,15 @@ class self.model, but as a class derived from self.model. We want to re-fetch

def __repr__(self, *args, **kwargs):
if self.model.polymorphic_query_multiline_output:
result = [repr(o) for o in self.all()]
return "[ " + ",\n ".join(result) + " ]"
result = ",\n ".join(repr(o) for o in self.all())
return f"[ {result} ]"
else:
return super().__repr__(*args, **kwargs)

class _p_list_class(list):
def __repr__(self, *args, **kwargs):
result = [repr(o) for o in self]
return "[ " + ",\n ".join(result) + " ]"
result = ",\n ".join(repr(o) for o in self)
return f"[ {result} ]"

def get_real_instances(self, base_result_objects=None):
"""
Expand Down
Loading

0 comments on commit 836a445

Please sign in to comment.