diff options
author | chillaranand <anand21nanda@gmail.com> | 2017-01-21 18:43:44 +0530 |
---|---|---|
committer | Tim Graham <timograham@gmail.com> | 2017-01-25 12:23:46 -0500 |
commit | d6eaf7c0183cd04b78f2a55e1d60bb7e59598310 (patch) | |
tree | ab02fd9949d4bfa23e27dea45e213ce334c883f0 | |
parent | dc165ec8e5698ffc6dee6b510f1f92c9fd7467fe (diff) | |
download | django-d6eaf7c0183cd04b78f2a55e1d60bb7e59598310.tar.gz |
Refs #23919 -- Replaced super(ClassName, self) with super().
339 files changed, 1221 insertions, 1296 deletions
diff --git a/django/conf/__init__.py b/django/conf/__init__.py index ec6efa8e96..2f2cec6f84 100644 --- a/django/conf/__init__.py +++ b/django/conf/__init__.py @@ -67,13 +67,13 @@ class LazySettings(LazyObject): self.__dict__.clear() else: self.__dict__.pop(name, None) - super(LazySettings, self).__setattr__(name, value) + super().__setattr__(name, value) def __delattr__(self, name): """ Delete a setting and clear it from cache if needed. """ - super(LazySettings, self).__delattr__(name) + super().__delattr__(name) self.__dict__.pop(name, None) def configure(self, default_settings=global_settings, **options): @@ -173,12 +173,12 @@ class UserSettingsHolder: def __setattr__(self, name, value): self._deleted.discard(name) - super(UserSettingsHolder, self).__setattr__(name, value) + super().__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): - super(UserSettingsHolder, self).__delattr__(name) + super().__delattr__(name) def __dir__(self): return sorted( diff --git a/django/contrib/admin/apps.py b/django/contrib/admin/apps.py index 194ec9f89d..6fa406cc44 100644 --- a/django/contrib/admin/apps.py +++ b/django/contrib/admin/apps.py @@ -19,5 +19,5 @@ class AdminConfig(SimpleAdminConfig): """The default AppConfig for admin which does autodiscovery.""" def ready(self): - super(AdminConfig, self).ready() + super().ready() self.module.autodiscover() diff --git a/django/contrib/admin/checks.py b/django/contrib/admin/checks.py index 354d0a3a9c..dad809a826 100644 --- a/django/contrib/admin/checks.py +++ b/django/contrib/admin/checks.py @@ -513,7 +513,7 @@ class BaseModelAdminChecks: class ModelAdminChecks(BaseModelAdminChecks): def check(self, admin_obj, **kwargs): - errors = super(ModelAdminChecks, self).check(admin_obj) + errors = super().check(admin_obj) errors.extend(self._check_save_as(admin_obj)) errors.extend(self._check_save_on_top(admin_obj)) errors.extend(self._check_inlines(admin_obj)) @@ -866,7 +866,7 @@ class ModelAdminChecks(BaseModelAdminChecks): class InlineModelAdminChecks(BaseModelAdminChecks): def check(self, inline_obj, **kwargs): - errors = super(InlineModelAdminChecks, self).check(inline_obj) + errors = super().check(inline_obj) parent_model = inline_obj.parent_model errors.extend(self._check_relation(inline_obj, parent_model)) errors.extend(self._check_exclude_of_parent_model(inline_obj, parent_model)) @@ -879,7 +879,7 @@ class InlineModelAdminChecks(BaseModelAdminChecks): def _check_exclude_of_parent_model(self, obj, parent_model): # Do not perform more specific checks if the base checks result in an # error. - errors = super(InlineModelAdminChecks, self)._check_exclude(obj) + errors = super()._check_exclude(obj) if errors: return [] diff --git a/django/contrib/admin/filters.py b/django/contrib/admin/filters.py index 923caa33e9..1b056e07e1 100644 --- a/django/contrib/admin/filters.py +++ b/django/contrib/admin/filters.py @@ -64,8 +64,7 @@ class SimpleListFilter(ListFilter): parameter_name = None def __init__(self, request, params, model, model_admin): - super(SimpleListFilter, self).__init__( - request, params, model, model_admin) + super().__init__(request, params, model, model_admin) if self.parameter_name is None: raise ImproperlyConfigured( "The list filter '%s' does not specify " @@ -122,8 +121,7 @@ class FieldListFilter(ListFilter): self.field = field self.field_path = field_path self.title = getattr(field, 'verbose_name', field_path) - super(FieldListFilter, self).__init__( - request, params, model, model_admin) + super().__init__(request, params, model, model_admin) for p in self.expected_parameters(): if p in params: value = params.pop(p) @@ -165,8 +163,7 @@ class RelatedFieldListFilter(FieldListFilter): self.lookup_kwarg_isnull = '%s__isnull' % field_path self.lookup_val = request.GET.get(self.lookup_kwarg) self.lookup_val_isnull = request.GET.get(self.lookup_kwarg_isnull) - super(RelatedFieldListFilter, self).__init__( - field, request, params, model, model_admin, field_path) + super().__init__(field, request, params, model, model_admin, field_path) self.lookup_choices = self.field_choices(field, request, model_admin) if hasattr(field, 'verbose_name'): self.lookup_title = field.verbose_name @@ -232,7 +229,7 @@ class BooleanFieldListFilter(FieldListFilter): self.lookup_kwarg2 = '%s__isnull' % field_path self.lookup_val = request.GET.get(self.lookup_kwarg) self.lookup_val2 = request.GET.get(self.lookup_kwarg2) - super(BooleanFieldListFilter, self).__init__(field, request, params, model, model_admin, field_path) + super().__init__(field, request, params, model, model_admin, field_path) if (self.used_parameters and self.lookup_kwarg in self.used_parameters and self.used_parameters[self.lookup_kwarg] in ('1', '0')): self.used_parameters[self.lookup_kwarg] = bool(int(self.used_parameters[self.lookup_kwarg])) @@ -274,8 +271,7 @@ class ChoicesFieldListFilter(FieldListFilter): self.lookup_kwarg_isnull = '%s__isnull' % field_path self.lookup_val = request.GET.get(self.lookup_kwarg) self.lookup_val_isnull = request.GET.get(self.lookup_kwarg_isnull) - super(ChoicesFieldListFilter, self).__init__( - field, request, params, model, model_admin, field_path) + super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] @@ -362,8 +358,7 @@ class DateFieldListFilter(FieldListFilter): (_('No date'), {self.field_generic + 'isnull': 'True'}), (_('Has date'), {self.field_generic + 'isnull': 'False'}), ) - super(DateFieldListFilter, self).__init__( - field, request, params, model, model_admin, field_path) + super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): params = [self.lookup_kwarg_since, self.lookup_kwarg_until] @@ -404,8 +399,7 @@ class AllValuesFieldListFilter(FieldListFilter): .distinct() .order_by(field.name) .values_list(field.name, flat=True)) - super(AllValuesFieldListFilter, self).__init__( - field, request, params, model, model_admin, field_path) + super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py index 17aac7a85b..dc150c6700 100644 --- a/django/contrib/admin/helpers.py +++ b/django/contrib/admin/helpers.py @@ -324,7 +324,7 @@ class InlineAdminForm(AdminForm): self.original = original self.show_url = original and view_on_site_url is not None self.absolute_url = view_on_site_url - super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields, readonly_fields, model_admin) + super().__init__(form, fieldsets, prepopulated_fields, readonly_fields, model_admin) def __iter__(self): for name, options in self.fieldsets: @@ -366,7 +366,7 @@ class InlineAdminForm(AdminForm): class InlineFieldset(Fieldset): def __init__(self, formset, *args, **kwargs): self.formset = formset - super(InlineFieldset, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __iter__(self): fk = getattr(self.formset, "fk", None) @@ -381,7 +381,7 @@ class AdminErrorList(forms.utils.ErrorList): Stores all errors for the form/formsets in an add/change stage view. """ def __init__(self, form, inline_formsets): - super(AdminErrorList, self).__init__() + super().__init__() if form.is_bound: self.extend(form.errors.values()) diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index 2d4bbbb933..ffca8163ec 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -519,7 +519,7 @@ class ModelAdmin(BaseModelAdmin): self.model = model self.opts = model._meta self.admin_site = admin_site - super(ModelAdmin, self).__init__() + super().__init__() def __str__(self): return "%s.%s" % (self.model._meta.app_label, self.__class__.__name__) @@ -1842,7 +1842,7 @@ class InlineModelAdmin(BaseModelAdmin): self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) - super(InlineModelAdmin, self).__init__() + super().__init__() if self.verbose_name is None: self.verbose_name = self.model._meta.verbose_name if self.verbose_name_plural is None: @@ -1936,7 +1936,7 @@ class InlineModelAdmin(BaseModelAdmin): raise ValidationError(msg, code='deleting_protected', params=params) def is_valid(self): - result = super(DeleteProtectedModelForm, self).is_valid() + result = super().is_valid() self.hand_clean_DELETE() return result @@ -1954,7 +1954,7 @@ class InlineModelAdmin(BaseModelAdmin): return list(form.base_fields) + list(self.get_readonly_fields(request, obj)) def get_queryset(self, request): - queryset = super(InlineModelAdmin, self).get_queryset(request) + queryset = super().get_queryset(request) if not self.has_change_permission(request): queryset = queryset.none() return queryset @@ -1966,7 +1966,7 @@ class InlineModelAdmin(BaseModelAdmin): # to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request) - return super(InlineModelAdmin, self).has_add_permission(request) + return super().has_add_permission(request) def has_change_permission(self, request, obj=None): opts = self.opts @@ -1987,7 +1987,7 @@ class InlineModelAdmin(BaseModelAdmin): # to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request, obj) - return super(InlineModelAdmin, self).has_delete_permission(request, obj) + return super().has_delete_permission(request, obj) class StackedInline(InlineModelAdmin): diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py index 6adf13fdb8..414c7ab983 100644 --- a/django/contrib/admin/sites.py +++ b/django/contrib/admin/sites.py @@ -198,7 +198,7 @@ class AdminSite: def get_urls(self): from django.conf.urls import url - urls = super(MyAdminSite, self).get_urls() + urls = super().get_urls() urls += [ url(r'^my_view/$', self.admin_view(some_view)) ] diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index c9dd6d7d30..81b533436d 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -291,7 +291,7 @@ class ResultList(list): # compatibility with existing admin templates. def __init__(self, form, *items): self.form = form - super(ResultList, self).__init__(*items) + super().__init__(*items) def results(cl): diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py index c55173d6c9..b890d9e3af 100644 --- a/django/contrib/admin/utils.py +++ b/django/contrib/admin/utils.py @@ -175,7 +175,7 @@ def get_deleted_objects(objs, opts, user, admin_site, using): class NestedObjects(Collector): def __init__(self, *args, **kwargs): - super(NestedObjects, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.edges = {} # {from_instance: [to_instances]} self.protected = set() self.model_objs = defaultdict(set) @@ -195,12 +195,12 @@ class NestedObjects(Collector): self.add_edge(None, obj) self.model_objs[obj._meta.model].add(obj) try: - return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs) + return super().collect(objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) def related_objects(self, related, objs): - qs = super(NestedObjects, self).related_objects(related, objs) + qs = super().related_objects(related, objs) return qs.select_related(related.field.name) def _nested(self, obj, seen, format_callback): diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py index 9f6fb412b2..380e0ad3a1 100644 --- a/django/contrib/admin/widgets.py +++ b/django/contrib/admin/widgets.py @@ -29,10 +29,10 @@ class FilteredSelectMultiple(forms.SelectMultiple): def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked - super(FilteredSelectMultiple, self).__init__(attrs, choices) + super().__init__(attrs, choices) def get_context(self, name, value, attrs=None): - context = super(FilteredSelectMultiple, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) context['widget']['attrs']['class'] = 'selectfilter' if self.is_stacked: context['widget']['attrs']['class'] += 'stacked' @@ -51,7 +51,7 @@ class AdminDateWidget(forms.DateInput): final_attrs = {'class': 'vDateField', 'size': '10'} if attrs is not None: final_attrs.update(attrs) - super(AdminDateWidget, self).__init__(attrs=final_attrs, format=format) + super().__init__(attrs=final_attrs, format=format) class AdminTimeWidget(forms.TimeInput): @@ -64,7 +64,7 @@ class AdminTimeWidget(forms.TimeInput): final_attrs = {'class': 'vTimeField', 'size': '8'} if attrs is not None: final_attrs.update(attrs) - super(AdminTimeWidget, self).__init__(attrs=final_attrs, format=format) + super().__init__(attrs=final_attrs, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): @@ -80,7 +80,7 @@ class AdminSplitDateTime(forms.SplitDateTimeWidget): forms.MultiWidget.__init__(self, widgets, attrs) def get_context(self, name, value, attrs): - context = super(AdminSplitDateTime, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) context['date_label'] = _('Date:') context['time_label'] = _('Time:') return context @@ -127,10 +127,10 @@ class ForeignKeyRawIdWidget(forms.TextInput): self.rel = rel self.admin_site = admin_site self.db = using - super(ForeignKeyRawIdWidget, self).__init__(attrs) + super().__init__(attrs) def get_context(self, name, value, attrs=None): - context = super(ForeignKeyRawIdWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) rel_to = self.rel.model if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite @@ -197,7 +197,7 @@ class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): template_name = 'admin/widgets/many_to_many_raw_id.html' def get_context(self, name, value, attrs=None): - context = super(ManyToManyRawIdWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) if self.rel.model in self.admin_site._registry: # The related object is registered with the same AdminSite context['widget']['attrs']['class'] = 'vManyToManyRawIdAdminField' @@ -310,7 +310,7 @@ class AdminTextareaWidget(forms.Textarea): final_attrs = {'class': 'vLargeTextField'} if attrs is not None: final_attrs.update(attrs) - super(AdminTextareaWidget, self).__init__(attrs=final_attrs) + super().__init__(attrs=final_attrs) class AdminTextInputWidget(forms.TextInput): @@ -318,7 +318,7 @@ class AdminTextInputWidget(forms.TextInput): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) - super(AdminTextInputWidget, self).__init__(attrs=final_attrs) + super().__init__(attrs=final_attrs) class AdminEmailInputWidget(forms.EmailInput): @@ -326,7 +326,7 @@ class AdminEmailInputWidget(forms.EmailInput): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) - super(AdminEmailInputWidget, self).__init__(attrs=final_attrs) + super().__init__(attrs=final_attrs) class AdminURLFieldWidget(forms.URLInput): @@ -336,17 +336,17 @@ class AdminURLFieldWidget(forms.URLInput): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) - super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) + super().__init__(attrs=final_attrs) def get_context(self, name, value, attrs): - context = super(AdminURLFieldWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) context['current_label'] = _('Currently:') context['change_label'] = _('Change:') context['widget']['href'] = smart_urlquote(context['widget']['value']) return context def format_value(self, value): - value = super(AdminURLFieldWidget, self).format_value(value) + value = super().format_value(value) return force_text(value) @@ -357,7 +357,7 @@ class AdminIntegerFieldWidget(forms.NumberInput): final_attrs = {'class': self.class_name} if attrs is not None: final_attrs.update(attrs) - super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) + super().__init__(attrs=final_attrs) class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py index f049c5f367..a3a70b095c 100644 --- a/django/contrib/admindocs/views.py +++ b/django/contrib/admindocs/views.py @@ -37,19 +37,19 @@ class BaseAdminDocsView(TemplateView): # Display an error message for people without docutils self.template_name = 'admin_doc/missing_docutils.html' return self.render_to_response(admin.site.each_context(request)) - return super(BaseAdminDocsView, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): kwargs.update({'root_path': reverse('admin:index')}) kwargs.update(admin.site.each_context(self.request)) - return super(BaseAdminDocsView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class BookmarkletsView(BaseAdminDocsView): template_name = 'admin_doc/bookmarklets.html' def get_context_data(self, **kwargs): - context = super(BookmarkletsView, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) context.update({ 'admin_url': "%s://%s%s" % ( self.request.scheme, self.request.get_host(), context['root_path']) @@ -88,7 +88,7 @@ class TemplateTagIndexView(BaseAdminDocsView): 'library': tag_library, }) kwargs.update({'tags': tags}) - return super(TemplateTagIndexView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class TemplateFilterIndexView(BaseAdminDocsView): @@ -122,7 +122,7 @@ class TemplateFilterIndexView(BaseAdminDocsView): 'library': tag_library, }) kwargs.update({'filters': filters}) - return super(TemplateFilterIndexView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class ViewIndexView(BaseAdminDocsView): @@ -146,7 +146,7 @@ class ViewIndexView(BaseAdminDocsView): 'name': name, }) kwargs.update({'views': views}) - return super(ViewIndexView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class ViewDetailView(BaseAdminDocsView): @@ -194,7 +194,7 @@ class ViewDetailView(BaseAdminDocsView): 'body': body, 'meta': metadata, }) - return super(ViewDetailView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class ModelIndexView(BaseAdminDocsView): @@ -203,7 +203,7 @@ class ModelIndexView(BaseAdminDocsView): def get_context_data(self, **kwargs): m_list = [m._meta for m in apps.get_models()] kwargs.update({'models': m_list}) - return super(ModelIndexView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class ModelDetailView(BaseAdminDocsView): @@ -333,7 +333,7 @@ class ModelDetailView(BaseAdminDocsView): 'fields': fields, 'methods': methods, }) - return super(ModelDetailView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class TemplateDetailView(BaseAdminDocsView): @@ -366,7 +366,7 @@ class TemplateDetailView(BaseAdminDocsView): 'name': template, 'templates': templates, }) - return super(TemplateDetailView, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) #################### diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py index f3c69023be..0f8e89567d 100644 --- a/django/contrib/auth/admin.py +++ b/django/contrib/auth/admin.py @@ -36,8 +36,7 @@ class GroupAdmin(admin.ModelAdmin): # Avoid a major performance hit resolving permission names which # triggers a content_type load: kwargs['queryset'] = qs.select_related('content_type') - return super(GroupAdmin, self).formfield_for_manytomany( - db_field, request=request, **kwargs) + return super().formfield_for_manytomany(db_field, request=request, **kwargs) @admin.register(User) @@ -69,7 +68,7 @@ class UserAdmin(admin.ModelAdmin): def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets - return super(UserAdmin, self).get_fieldsets(request, obj) + return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ @@ -79,7 +78,7 @@ class UserAdmin(admin.ModelAdmin): if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) - return super(UserAdmin, self).get_form(request, obj, **defaults) + return super().get_form(request, obj, **defaults) def get_urls(self): return [ @@ -88,13 +87,13 @@ class UserAdmin(admin.ModelAdmin): self.admin_site.admin_view(self.user_change_password), name='auth_user_password_change', ), - ] + super(UserAdmin, self).get_urls() + ] + super().get_urls() def lookup_allowed(self, lookup, value): # See #20078: we don't want to allow any lookups involving passwords. if lookup.startswith('password'): return False - return super(UserAdmin, self).lookup_allowed(lookup, value) + return super().lookup_allowed(lookup, value) @sensitive_post_parameters_m @csrf_protect_m @@ -127,8 +126,7 @@ class UserAdmin(admin.ModelAdmin): 'username_help_text': username_field.help_text, } extra_context.update(defaults) - return super(UserAdmin, self).add_view(request, form_url, - extra_context) + return super().add_view(request, form_url, extra_context) @sensitive_post_parameters_m def user_change_password(self, request, id, form_url=''): @@ -207,5 +205,4 @@ class UserAdmin(admin.ModelAdmin): if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST: request.POST = request.POST.copy() request.POST['_continue'] = 1 - return super(UserAdmin, self).response_add(request, obj, - post_url_continue) + return super().response_add(request, obj, post_url_continue) diff --git a/django/contrib/auth/base_user.py b/django/contrib/auth/base_user.py index 4ec18bee17..de33baf3d7 100644 --- a/django/contrib/auth/base_user.py +++ b/django/contrib/auth/base_user.py @@ -61,7 +61,7 @@ class AbstractBaseUser(models.Model): return getattr(self, self.USERNAME_FIELD) def __init__(self, *args, **kwargs): - super(AbstractBaseUser, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Stores the raw password if set_password() is called so that it can # be passed to password_changed() after the model is saved. self._password = None @@ -73,7 +73,7 @@ class AbstractBaseUser(models.Model): setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username())) def save(self, *args, **kwargs): - super(AbstractBaseUser, self).save(*args, **kwargs) + super().save(*args, **kwargs) if self._password is not None: password_validation.password_changed(self._password, self) self._password = None diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index 51c513cb67..0a7961d649 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -24,7 +24,7 @@ class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' def get_context(self, name, value, attrs): - context = super(ReadOnlyPasswordHashWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) summary = [] if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX): summary.append({'label': ugettext("No password set.")}) @@ -45,7 +45,7 @@ class ReadOnlyPasswordHashField(forms.Field): def __init__(self, *args, **kwargs): kwargs.setdefault("required", False) - super(ReadOnlyPasswordHashField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def bound_data(self, data, initial): # Always return initial because the widget doesn't @@ -58,7 +58,7 @@ class ReadOnlyPasswordHashField(forms.Field): class UsernameField(forms.CharField): def to_python(self, value): - return unicodedata.normalize('NFKC', super(UsernameField, self).to_python(value)) + return unicodedata.normalize('NFKC', super().to_python(value)) class UserCreationForm(forms.ModelForm): @@ -88,7 +88,7 @@ class UserCreationForm(forms.ModelForm): field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): - super(UserCreationForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) @@ -105,7 +105,7 @@ class UserCreationForm(forms.ModelForm): return password2 def save(self, commit=True): - user = super(UserCreationForm, self).save(commit=False) + user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() @@ -128,7 +128,7 @@ class UserChangeForm(forms.ModelForm): field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): - super(UserChangeForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) f = self.fields.get('user_permissions') if f is not None: f.queryset = f.queryset.select_related('content_type') @@ -170,7 +170,7 @@ class AuthenticationForm(forms.Form): """ self.request = request self.user_cache = None - super(AuthenticationForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Set the label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) @@ -310,7 +310,7 @@ class SetPasswordForm(forms.Form): def __init__(self, user, *args, **kwargs): self.user = user - super(SetPasswordForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') @@ -384,7 +384,7 @@ class AdminPasswordChangeForm(forms.Form): def __init__(self, user, *args, **kwargs): self.user = user - super(AdminPasswordChangeForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean_password2(self): password1 = self.cleaned_data.get('password1') @@ -410,7 +410,7 @@ class AdminPasswordChangeForm(forms.Form): @property def changed_data(self): - data = super(AdminPasswordChangeForm, self).changed_data + data = super().changed_data for name in self.fields.keys(): if name not in data: return [] diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py index d9fd70b6f1..b027d2c326 100644 --- a/django/contrib/auth/management/commands/createsuperuser.py +++ b/django/contrib/auth/management/commands/createsuperuser.py @@ -22,7 +22,7 @@ class Command(BaseCommand): requires_migrations_checks = True def __init__(self, *args, **kwargs): - super(Command, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.UserModel = get_user_model() self.username_field = self.UserModel._meta.get_field(self.UserModel.USERNAME_FIELD) @@ -56,7 +56,7 @@ class Command(BaseCommand): def execute(self, *args, **options): self.stdin = options.get('stdin', sys.stdin) # Used for testing - return super(Command, self).execute(*args, **options) + return super().execute(*args, **options) def handle(self, *args, **options): username = options[self.UserModel.USERNAME_FIELD] diff --git a/django/contrib/auth/mixins.py b/django/contrib/auth/mixins.py index e52311670f..0b52c0286d 100644 --- a/django/contrib/auth/mixins.py +++ b/django/contrib/auth/mixins.py @@ -52,7 +52,7 @@ class LoginRequiredMixin(AccessMixin): def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() - return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) class PermissionRequiredMixin(AccessMixin): @@ -88,7 +88,7 @@ class PermissionRequiredMixin(AccessMixin): def dispatch(self, request, *args, **kwargs): if not self.has_permission(): return self.handle_no_permission() - return super(PermissionRequiredMixin, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) class UserPassesTestMixin(AccessMixin): @@ -112,4 +112,4 @@ class UserPassesTestMixin(AccessMixin): user_test_result = self.get_test_func()() if not user_test_result: return self.handle_no_permission() - return super(UserPassesTestMixin, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index bd185b58be..7476a69517 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -340,7 +340,7 @@ class AbstractUser(AbstractBaseUser, PermissionsMixin): abstract = True def clean(self): - super(AbstractUser, self).clean() + super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): diff --git a/django/contrib/auth/views.py b/django/contrib/auth/views.py index cca52a6105..6208b5fe41 100644 --- a/django/contrib/auth/views.py +++ b/django/contrib/auth/views.py @@ -63,7 +63,7 @@ class LoginView(SuccessURLAllowedHostsMixin, FormView): "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) - return super(LoginView, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) def get_success_url(self): """Ensure the user-originating redirection URL is safe.""" @@ -89,7 +89,7 @@ class LoginView(SuccessURLAllowedHostsMixin, FormView): return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): - context = super(LoginView, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update({ self.redirect_field_name: self.get_success_url(), @@ -125,7 +125,7 @@ class LogoutView(SuccessURLAllowedHostsMixin, TemplateView): if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) - return super(LogoutView, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) def get_next_page(self): if self.next_page is not None: @@ -153,7 +153,7 @@ class LogoutView(SuccessURLAllowedHostsMixin, TemplateView): return next_page def get_context_data(self, **kwargs): - context = super(LogoutView, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update({ 'site': current_site, @@ -356,7 +356,7 @@ class PasswordContextMixin: extra_context = None def get_context_data(self, **kwargs): - context = super(PasswordContextMixin, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) context['title'] = self.title if self.extra_context is not None: context.update(self.extra_context) @@ -377,7 +377,7 @@ class PasswordResetView(PasswordContextMixin, FormView): @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): - return super(PasswordResetView, self).dispatch(*args, **kwargs) + return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { @@ -391,7 +391,7 @@ class PasswordResetView(PasswordContextMixin, FormView): 'extra_email_context': self.extra_email_context, } form.save(**opts) - return super(PasswordResetView, self).form_valid(form) + return super().form_valid(form) INTERNAL_RESET_URL_TOKEN = 'set-password' @@ -426,7 +426,7 @@ class PasswordResetConfirmView(PasswordContextMixin, FormView): if self.token_generator.check_token(self.user, session_token): # If the token is valid, display the password reset form. self.validlink = True - return super(PasswordResetConfirmView, self).dispatch(*args, **kwargs) + return super().dispatch(*args, **kwargs) else: if self.token_generator.check_token(self.user, token): # Store the token in the session and redirect to the @@ -450,7 +450,7 @@ class PasswordResetConfirmView(PasswordContextMixin, FormView): return user def get_form_kwargs(self): - kwargs = super(PasswordResetConfirmView, self).get_form_kwargs() + kwargs = super().get_form_kwargs() kwargs['user'] = self.user return kwargs @@ -459,10 +459,10 @@ class PasswordResetConfirmView(PasswordContextMixin, FormView): if self.post_reset_login: auth_login(self.request, user) del self.request.session[INTERNAL_RESET_SESSION_TOKEN] - return super(PasswordResetConfirmView, self).form_valid(form) + return super().form_valid(form) def get_context_data(self, **kwargs): - context = super(PasswordResetConfirmView, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) if self.validlink: context['validlink'] = True else: @@ -479,7 +479,7 @@ class PasswordResetCompleteView(PasswordContextMixin, TemplateView): title = _('Password reset complete') def get_context_data(self, **kwargs): - context = super(PasswordResetCompleteView, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) context['login_url'] = resolve_url(settings.LOGIN_URL) return context @@ -545,10 +545,10 @@ class PasswordChangeView(PasswordContextMixin, FormView): @method_decorator(csrf_protect) @method_decorator(login_required) def dispatch(self, *args, **kwargs): - return super(PasswordChangeView, self).dispatch(*args, **kwargs) + return super().dispatch(*args, **kwargs) def get_form_kwargs(self): - kwargs = super(PasswordChangeView, self).get_form_kwargs() + kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs @@ -557,7 +557,7 @@ class PasswordChangeView(PasswordContextMixin, FormView): # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) - return super(PasswordChangeView, self).form_valid(form) + return super().form_valid(form) class PasswordChangeDoneView(PasswordContextMixin, TemplateView): @@ -566,4 +566,4 @@ class PasswordChangeDoneView(PasswordContextMixin, TemplateView): @method_decorator(login_required) def dispatch(self, *args, **kwargs): - return super(PasswordChangeDoneView, self).dispatch(*args, **kwargs) + return super().dispatch(*args, **kwargs) diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py index efffbfd77a..37a9df14a0 100644 --- a/django/contrib/contenttypes/fields.py +++ b/django/contrib/contenttypes/fields.py @@ -261,12 +261,10 @@ class GenericRel(ForeignObjectRel): """ def __init__(self, field, to, related_name=None, related_query_name=None, limit_choices_to=None): - super(GenericRel, self).__init__( - field, to, - related_name=related_query_name or '+', + super().__init__( + field, to, related_name=related_query_name or '+', related_query_name=related_query_name, - limit_choices_to=limit_choices_to, - on_delete=DO_NOTHING, + limit_choices_to=limit_choices_to, on_delete=DO_NOTHING, ) @@ -303,15 +301,14 @@ class GenericRelation(ForeignObject): # isn't direct, the join is generated reverse along foreign key. So, # the from_field is object_id field, to_field is pk because of the # reverse join. - super(GenericRelation, self).__init__( - to, from_fields=[object_id_field], to_fields=[], **kwargs) + super().__init__(to, from_fields=[object_id_field], to_fields=[], **kwargs) self.object_id_field_name = object_id_field self.content_type_field_name = content_type_field self.for_concrete_model = for_concrete_model def check(self, **kwargs): - errors = super(GenericRelation, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_generic_foreign_key_existence()) return errors @@ -403,7 +400,7 @@ class GenericRelation(ForeignObject): def contribute_to_class(self, cls, name, **kwargs): kwargs['private_only'] = True - super(GenericRelation, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) self.model = cls setattr(cls, self.name, ReverseGenericManyToOneDescriptor(self.remote_field)) @@ -480,7 +477,7 @@ def create_generic_related_manager(superclass, rel): class GenericRelatedObjectManager(superclass): def __init__(self, instance=None): - super(GenericRelatedObjectManager, self).__init__() + super().__init__() self.instance = instance @@ -521,12 +518,12 @@ def create_generic_related_manager(superclass, rel): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): - queryset = super(GenericRelatedObjectManager, self).get_queryset() + queryset = super().get_queryset() return self._apply_rel_filters(queryset) def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: - queryset = super(GenericRelatedObjectManager, self).get_queryset() + queryset = super().get_queryset() queryset._add_hints(instance=instances[0]) queryset = queryset.using(queryset._db or self._db) @@ -634,21 +631,21 @@ def create_generic_related_manager(superclass, rel): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) - return super(GenericRelatedObjectManager, self).using(db).create(**kwargs) + return super().using(db).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) - return super(GenericRelatedObjectManager, self).using(db).get_or_create(**kwargs) + return super().using(db).get_or_create(**kwargs) get_or_create.alters_data = True def update_or_create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) - return super(GenericRelatedObjectManager, self).using(db).update_or_create(**kwargs) + return super().using(db).update_or_create(**kwargs) update_or_create.alters_data = True return GenericRelatedObjectManager diff --git a/django/contrib/contenttypes/forms.py b/django/contrib/contenttypes/forms.py index 8e88c9a1cd..32b4012d8a 100644 --- a/django/contrib/contenttypes/forms.py +++ b/django/contrib/contenttypes/forms.py @@ -27,11 +27,7 @@ class BaseGenericInlineFormSet(BaseModelFormSet): self.instance, for_concrete_model=self.for_concrete_model), self.ct_fk_field.name: self.instance.pk, }) - super(BaseGenericInlineFormSet, self).__init__( - queryset=qs, data=data, files=files, - prefix=prefix, - **kwargs - ) + super().__init__(queryset=qs, data=data, files=files, prefix=prefix, **kwargs) @classmethod def get_default_prefix(cls): diff --git a/django/contrib/contenttypes/management/__init__.py b/django/contrib/contenttypes/management/__init__.py index 6799ef8a23..a77c9d67b9 100644 --- a/django/contrib/contenttypes/management/__init__.py +++ b/django/contrib/contenttypes/management/__init__.py @@ -8,7 +8,7 @@ class RenameContentType(migrations.RunPython): self.app_label = app_label self.old_model = old_model self.new_model = new_model - super(RenameContentType, self).__init__(self.rename_forward, self.rename_backward) + super().__init__(self.rename_forward, self.rename_backward) def _rename(self, apps, schema_editor, old_model, new_model): ContentType = apps.get_model('contenttypes', 'ContentType') diff --git a/django/contrib/contenttypes/models.py b/django/contrib/contenttypes/models.py index 9fe4a56767..ce9afdb8ad 100644 --- a/django/contrib/contenttypes/models.py +++ b/django/contrib/contenttypes/models.py @@ -10,7 +10,7 @@ class ContentTypeManager(models.Manager): use_in_migrations = True def __init__(self, *args, **kwargs): - super(ContentTypeManager, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Cache shared by all the get_for_* methods to speed up # ContentType retrieval. self._cache = {} diff --git a/django/contrib/flatpages/forms.py b/django/contrib/flatpages/forms.py index 4735c1ca95..3933df8e4e 100644 --- a/django/contrib/flatpages/forms.py +++ b/django/contrib/flatpages/forms.py @@ -55,4 +55,4 @@ class FlatpageForm(forms.ModelForm): params={'url': url, 'site': site}, ) - return super(FlatpageForm, self).clean() + return super().clean() diff --git a/django/contrib/gis/admin/options.py b/django/contrib/gis/admin/options.py index 4ae61661d3..20bfa74379 100644 --- a/django/contrib/gis/admin/options.py +++ b/django/contrib/gis/admin/options.py @@ -46,7 +46,7 @@ class GeoModelAdmin(ModelAdmin): @property def media(self): "Injects OpenLayers JavaScript into the admin." - media = super(GeoModelAdmin, self).media + media = super().media media.add_js([self.openlayers_url]) media.add_js(self.extra_js) return media @@ -62,7 +62,7 @@ class GeoModelAdmin(ModelAdmin): kwargs['widget'] = self.get_map_widget(db_field) return db_field.formfield(**kwargs) else: - return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs) + return super().formfield_for_dbfield(db_field, request, **kwargs) def get_map_widget(self, db_field): """ diff --git a/django/contrib/gis/db/backends/base/operations.py b/django/contrib/gis/db/backends/base/operations.py index 23989da9fc..3d46f5f46c 100644 --- a/django/contrib/gis/db/backends/base/operations.py +++ b/django/contrib/gis/db/backends/base/operations.py @@ -116,7 +116,7 @@ class BaseSpatialOperations: raise NotImplementedError( "%s spatial aggregation is not supported by this database backend." % expression.name ) - super(BaseSpatialOperations, self).check_expression_support(expression) + super().check_expression_support(expression) def spatial_aggregate_name(self, agg_name): raise NotImplementedError('Aggregate support not implemented for this spatial backend.') diff --git a/django/contrib/gis/db/backends/mysql/operations.py b/django/contrib/gis/db/backends/mysql/operations.py index 7d8adbf158..6408d76fa4 100644 --- a/django/contrib/gis/db/backends/mysql/operations.py +++ b/django/contrib/gis/db/backends/mysql/operations.py @@ -97,7 +97,7 @@ class MySQLOperations(BaseSpatialOperations, DatabaseOperations): return placeholder def get_db_converters(self, expression): - converters = super(MySQLOperations, self).get_db_converters(expression) + converters = super().get_db_converters(expression) if isinstance(expression.output_field, GeometryField) and self.uses_invalid_empty_geometry_collection: converters.append(self.convert_invalid_empty_geometry_collection) return converters diff --git a/django/contrib/gis/db/backends/mysql/schema.py b/django/contrib/gis/db/backends/mysql/schema.py index a9b1b4867a..699fab60e9 100644 --- a/django/contrib/gis/db/backends/mysql/schema.py +++ b/django/contrib/gis/db/backends/mysql/schema.py @@ -12,18 +12,18 @@ class MySQLGISSchemaEditor(DatabaseSchemaEditor): sql_drop_spatial_index = 'DROP INDEX %(index)s ON %(table)s' def __init__(self, *args, **kwargs): - super(MySQLGISSchemaEditor, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.geometry_sql = [] def skip_default(self, field): return ( - super(MySQLGISSchemaEditor, self).skip_default(field) or + super().skip_default(field) or # Geometry fields are stored as BLOB/TEXT and can't have defaults. isinstance(field, GeometryField) ) def column_sql(self, model, field, include_default=False): - column_sql = super(MySQLGISSchemaEditor, self).column_sql(model, field, include_default) + column_sql = super().column_sql(model, field, include_default) # MySQL doesn't support spatial indexes on NULL columns if isinstance(field, GeometryField) and field.spatial_index and not field.null: qn = self.connection.ops.quote_name @@ -38,11 +38,11 @@ class MySQLGISSchemaEditor(DatabaseSchemaEditor): return column_sql def create_model(self, model): - super(MySQLGISSchemaEditor, self).create_model(model) + super().create_model(model) self.create_spatial_indexes() def add_field(self, model, field): - super(MySQLGISSchemaEditor, self).add_field(model, field) + super().add_field(model, field) self.create_spatial_indexes() def remove_field(self, model, field): @@ -60,7 +60,7 @@ class MySQLGISSchemaEditor(DatabaseSchemaEditor): "if your storage engine doesn't support them).", sql ) - super(MySQLGISSchemaEditor, self).remove_field(model, field) + super().remove_field(model, field) def _create_spatial_index_name(self, model, field): return '%s_%s_id' % (model._meta.db_table, field.column) diff --git a/django/contrib/gis/db/backends/oracle/operations.py b/django/contrib/gis/db/backends/oracle/operations.py index a431b916be..6fc4fb69aa 100644 --- a/django/contrib/gis/db/backends/oracle/operations.py +++ b/django/contrib/gis/db/backends/oracle/operations.py @@ -49,7 +49,7 @@ class SDORelate(SpatialOperator): def as_sql(self, connection, lookup, template_params, sql_params): template_params['mask'] = sql_params.pop() - return super(SDORelate, self).as_sql(connection, lookup, template_params, sql_params) + return super().as_sql(connection, lookup, template_params, sql_params) class SDOIsValid(SpatialOperator): @@ -143,10 +143,10 @@ class OracleOperations(BaseSpatialOperations, DatabaseOperations): return unsupported def geo_quote_name(self, name): - return super(OracleOperations, self).geo_quote_name(name).upper() + return super().geo_quote_name(name).upper() def get_db_converters(self, expression): - converters = super(OracleOperations, self).get_db_converters(expression) + converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() geometry_fields = ( 'PointField', 'GeometryField', 'LineStringField', @@ -271,4 +271,4 @@ class OracleOperations(BaseSpatialOperations, DatabaseOperations): """ if placeholder == 'NULL': return [] - return super(OracleOperations, self).modify_insert_params(placeholder, params) + return super().modify_insert_params(placeholder, params) diff --git a/django/contrib/gis/db/backends/oracle/schema.py b/django/contrib/gis/db/backends/oracle/schema.py index 78470da07d..d90e6cfad6 100644 --- a/django/contrib/gis/db/backends/oracle/schema.py +++ b/django/contrib/gis/db/backends/oracle/schema.py @@ -25,14 +25,14 @@ class OracleGISSchemaEditor(DatabaseSchemaEditor): ) def __init__(self, *args, **kwargs): - super(OracleGISSchemaEditor, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.geometry_sql = [] def geo_quote_name(self, name): return self.connection.ops.geo_quote_name(name) def column_sql(self, model, field, include_default=False): - column_sql = super(OracleGISSchemaEditor, self).column_sql(model, field, include_default) + column_sql = super().column_sql(model, field, include_default) if isinstance(field, GeometryField): db_table = model._meta.db_table self.geometry_sql.append( @@ -58,17 +58,17 @@ class OracleGISSchemaEditor(DatabaseSchemaEditor): return column_sql def create_model(self, model): - super(OracleGISSchemaEditor, self).create_model(model) + super().create_model(model) self.run_geometry_sql() def delete_model(self, model): - super(OracleGISSchemaEditor, self).delete_model(model) + super().delete_model(model) self.execute(self.sql_clear_geometry_table_metadata % { 'table': self.geo_quote_name(model._meta.db_table), }) def add_field(self, model, field): - super(OracleGISSchemaEditor, self).add_field(model, field) + super().add_field(model, field) self.run_geometry_sql() def remove_field(self, model, field): @@ -81,7 +81,7 @@ class OracleGISSchemaEditor(DatabaseSchemaEditor): self.execute(self.sql_drop_spatial_index % { 'index': self.quote_name(self._create_spatial_index_name(model, field)), }) - super(OracleGISSchemaEditor, self).remove_field(model, field) + super().remove_field(model, field) def run_geometry_sql(self): for sql in self.geometry_sql: diff --git a/django/contrib/gis/db/backends/postgis/base.py b/django/contrib/gis/db/backends/postgis/base.py index 203e3ba075..c14df8ccfa 100644 --- a/django/contrib/gis/db/backends/postgis/base.py +++ b/django/contrib/gis/db/backends/postgis/base.py @@ -12,14 +12,14 @@ class DatabaseWrapper(Psycopg2DatabaseWrapper): SchemaEditorClass = PostGISSchemaEditor def __init__(self, *args, **kwargs): - super(DatabaseWrapper, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if kwargs.get('alias', '') != NO_DB_ALIAS: self.features = DatabaseFeatures(self) self.ops = PostGISOperations(self) self.introspection = PostGISIntrospection(self) def prepare_database(self): - super(DatabaseWrapper, self).prepare_database() + super().prepare_database() # Check that postgis extension is installed. with self.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") diff --git a/django/contrib/gis/db/backends/postgis/introspection.py b/django/contrib/gis/db/backends/postgis/introspection.py index 5e7c34aeed..43007c72d3 100644 --- a/django/contrib/gis/db/backends/postgis/introspection.py +++ b/django/contrib/gis/db/backends/postgis/introspection.py @@ -79,7 +79,7 @@ class PostGISIntrospection(DatabaseIntrospection): # performed -- in other words, when this function is called. self.postgis_types_reverse = self.get_postgis_types() self.data_types_reverse.update(self.postgis_types_reverse) - return super(PostGISIntrospection, self).get_field_type(data_type, description) + return super().get_field_type(data_type, description) def get_geometry_type(self, table_name, geo_col): """ diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py index 678c420c23..e29b2558d9 100644 --- a/django/contrib/gis/db/backends/postgis/operations.py +++ b/django/contrib/gis/db/backends/postgis/operations.py @@ -29,7 +29,7 @@ class PostGISOperator(SpatialOperator): # polygons. If the raster argument is set to BILATERAL, then the # operator cannot handle mixed geom-raster lookups. self.raster = raster - super(PostGISOperator, self).__init__(**kwargs) + super().__init__(**kwargs) def as_sql(self, connection, lookup, template_params, *args): if lookup.lhs.output_field.geography and not self.geography: @@ -37,7 +37,7 @@ class PostGISOperator(SpatialOperator): 'function/operator.' % (self.func or self.op,)) template_params = self.check_raster(lookup, template_params) - return super(PostGISOperator, self).as_sql(connection, lookup, template_params, *args) + return super().as_sql(connection, lookup, template_params, *args) def check_raster(self, lookup, template_params): # Get rhs value. @@ -100,7 +100,7 @@ class PostGISDistanceOperator(PostGISOperator): else: template_params.update({'op': self.op, 'func': connection.ops.spatial_function_name('DistanceSphere')}) return sql_template % template_params, sql_params - return super(PostGISDistanceOperator, self).as_sql(connection, lookup, template_params, sql_params) + return super().as_sql(connection, lookup, template_params, sql_params) class PostGISOperations(BaseSpatialOperations, DatabaseOperations): @@ -149,7 +149,7 @@ class PostGISOperations(BaseSpatialOperations, DatabaseOperations): unsupported_functions = set() def __init__(self, connection): - super(PostGISOperations, self).__init__(connection) + super().__init__(connection) prefix = self.geom_func_prefix diff --git a/django/contrib/gis/db/backends/postgis/schema.py b/django/contrib/gis/db/backends/postgis/schema.py index d88901b50d..7a7f88f02d 100644 --- a/django/contrib/gis/db/backends/postgis/schema.py +++ b/django/contrib/gis/db/backends/postgis/schema.py @@ -15,11 +15,11 @@ class PostGISSchemaEditor(DatabaseSchemaEditor): def _field_should_be_indexed(self, model, field): if getattr(field, 'spatial_index', False): return True - return super(PostGISSchemaEditor, self)._field_should_be_indexed(model, field) + return super()._field_should_be_indexed(model, field) def _create_index_sql(self, model, fields, suffix="", sql=None): if len(fields) != 1 or not hasattr(fields[0], 'geodetic'): - return super(PostGISSchemaEditor, self)._create_index_sql(model, fields, suffix=suffix, sql=sql) + return super()._create_index_sql(model, fields, suffix=suffix, sql=sql) field = fields[0] field_column = self.quote_name(field.column) @@ -45,9 +45,7 @@ class PostGISSchemaEditor(DatabaseSchemaEditor): Special case when dimension changed. """ if not hasattr(old_field, 'dim') or not hasattr(new_field, 'dim'): - return super(PostGISSchemaEditor, self)._alter_column_type_sql( - table, old_field, new_field, new_type - ) + return super()._alter_column_type_sql(table, old_field, new_field, new_type) if old_field.dim == 2 and new_field.dim == 3: sql_alter = self.sql_alter_column_to_3d diff --git a/django/contrib/gis/db/backends/spatialite/base.py b/django/contrib/gis/db/backends/spatialite/base.py index 287c643ce8..2b2a342b11 100644 --- a/django/contrib/gis/db/backends/spatialite/base.py +++ b/django/contrib/gis/db/backends/spatialite/base.py @@ -34,10 +34,10 @@ class DatabaseWrapper(SQLiteDatabaseWrapper): 'Make sure it is in your library path, or set ' 'SPATIALITE_LIBRARY_PATH in your settings.' ) - super(DatabaseWrapper, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def get_new_connection(self, conn_params): - conn = super(DatabaseWrapper, self).get_new_connection(conn_params) + conn = super().get_new_connection(conn_params) # Enabling extension loading on the SQLite connection. try: conn.enable_load_extension(True) @@ -59,7 +59,7 @@ class DatabaseWrapper(SQLiteDatabaseWrapper): return conn def prepare_database(self): - super(DatabaseWrapper, self).prepare_database() + super().prepare_database() # Check if spatial metadata have been initialized in the database with self.cursor() as cursor: cursor.execute("PRAGMA table_info(geometry_columns);") diff --git a/django/contrib/gis/db/backends/spatialite/introspection.py b/django/contrib/gis/db/backends/spatialite/introspection.py index 467e3a44f7..e06cd5a4e1 100644 --- a/django/contrib/gis/db/backends/spatialite/introspection.py +++ b/django/contrib/gis/db/backends/spatialite/introspection.py @@ -61,7 +61,7 @@ class SpatiaLiteIntrospection(DatabaseIntrospection): return field_type, field_params def get_constraints(self, cursor, table_name): - constraints = super(SpatiaLiteIntrospection, self).get_constraints(cursor, table_name) + constraints = super().get_constraints(cursor, table_name) cursor.execute('SELECT f_geometry_column ' 'FROM geometry_columns ' 'WHERE f_table_name=%s AND spatial_index_enabled=1', (table_name,)) diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py index 5fab0b4df7..03e994ac9d 100644 --- a/django/contrib/gis/db/backends/spatialite/operations.py +++ b/django/contrib/gis/db/backends/spatialite/operations.py @@ -28,7 +28,7 @@ class SpatiaLiteDistanceOperator(SpatialOperator): }) sql_params.insert(1, len(lookup.rhs) == 3 and lookup.rhs[-1] == 'spheroid') return sql_template % template_params, sql_params - return super(SpatiaLiteDistanceOperator, self).as_sql(connection, lookup, template_params, sql_params) + return super().as_sql(connection, lookup, template_params, sql_params) class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): @@ -261,7 +261,7 @@ class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): return SpatialiteSpatialRefSys def get_db_converters(self, expression): - converters = super(SpatiaLiteOperations, self).get_db_converters(expression) + converters = super().get_db_converters(expression) if hasattr(expression.output_field, 'geom_type'): converters.append(self.convert_geometry) return converters diff --git a/django/contrib/gis/db/backends/spatialite/schema.py b/django/contrib/gis/db/backends/spatialite/schema.py index 401fbf2b78..6f4e3380db 100644 --- a/django/contrib/gis/db/backends/spatialite/schema.py +++ b/django/contrib/gis/db/backends/spatialite/schema.py @@ -28,7 +28,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): ] def __init__(self, *args, **kwargs): - super(SpatialiteSchemaEditor, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.geometry_sql = [] def geo_quote_name(self, name): @@ -37,7 +37,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): def column_sql(self, model, field, include_default=False): from django.contrib.gis.db.models.fields import GeometryField if not isinstance(field, GeometryField): - return super(SpatialiteSchemaEditor, self).column_sql(model, field, include_default) + return super().column_sql(model, field, include_default) # Geometry columns are created by the `AddGeometryColumn` function self.geometry_sql.append( @@ -75,7 +75,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): ) def create_model(self, model): - super(SpatialiteSchemaEditor, self).create_model(model) + super().create_model(model) # Create geometry columns for sql in self.geometry_sql: self.execute(sql) @@ -98,7 +98,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): ) except DatabaseError: pass - super(SpatialiteSchemaEditor, self).delete_model(model, **kwargs) + super().delete_model(model, **kwargs) def add_field(self, model, field): from django.contrib.gis.db.models.fields import GeometryField @@ -109,7 +109,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): self.execute(sql) self.geometry_sql = [] else: - super(SpatialiteSchemaEditor, self).add_field(model, field) + super().add_field(model, field) def remove_field(self, model, field): from django.contrib.gis.db.models.fields import GeometryField @@ -121,7 +121,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): if isinstance(field, GeometryField): self._remake_table(model, delete_field=field) else: - super(SpatialiteSchemaEditor, self).remove_field(model, field) + super().remove_field(model, field) def alter_db_table(self, model, old_db_table, new_db_table): from django.contrib.gis.db.models.fields import GeometryField @@ -135,7 +135,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor): } ) # Alter table - super(SpatialiteSchemaEditor, self).alter_db_table(model, old_db_table, new_db_table) + super().alter_db_table(model, old_db_table, new_db_table) # Repoint any straggler names for geom_table in self.geometry_tables: try: diff --git a/django/contrib/gis/db/models/aggregates.py b/django/contrib/gis/db/models/aggregates.py index 416481f9ca..95dce944c5 100644 --- a/django/contrib/gis/db/models/aggregates.py +++ b/django/contrib/gis/db/models/aggregates.py @@ -13,7 +13,7 @@ class GeoAggregate(Aggregate): # we get the spatial_aggregate_name connection.ops.check_expression_support(self) self.function = connection.ops.spatial_aggregate_name(self.name) - return super(GeoAggregate, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) def as_oracle(self, compiler, connection): if not hasattr(self, 'tolerance'): @@ -24,7 +24,7 @@ class GeoAggregate(Aggregate): return self.as_sql(compiler, connection) def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - c = super(GeoAggregate, self).resolve_expression(query, allow_joins, reuse, summarize, for_save) + c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) for expr in c.get_source_expressions(): if not hasattr(expr.field, 'geom_type'): raise ValueError('Geospatial aggregates only allowed on geometry fields.') @@ -40,7 +40,7 @@ class Extent(GeoAggregate): is_extent = '2D' def __init__(self, expression, **extra): - super(Extent, self).__init__(expression, output_field=ExtentField(), **extra) + super().__init__(expression, output_field=ExtentField(), **extra) def convert_value(self, value, expression, connection, context): return connection.ops.convert_extent(value, context.get('transformed_srid')) @@ -51,7 +51,7 @@ class Extent3D(GeoAggregate): is_extent = '3D' def __init__(self, expression, **extra): - super(Extent3D, self).__init__(expression, output_field=ExtentField(), **extra) + super().__init__(expression, output_field=ExtentField(), **extra) def convert_value(self, value, expression, connection, context): return connection.ops.convert_extent3d(value, context.get('transformed_srid')) diff --git a/django/contrib/gis/db/models/fields.py b/django/contrib/gis/db/models/fields.py index 101975ed87..d6cd529dc1 100644 --- a/django/contrib/gis/db/models/fields.py +++ b/django/contrib/gis/db/models/fields.py @@ -110,10 +110,10 @@ class BaseSpatialField(Field): # first parameter, so this works like normal fields. kwargs['verbose_name'] = verbose_name - super(BaseSpatialField, self).__init__(**kwargs) + super().__init__(**kwargs) def deconstruct(self): - name, path, args, kwargs = super(BaseSpatialField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() # Always include SRID for less fragility; include spatial index if it's # not the default value. kwargs['srid'] = self.srid @@ -207,7 +207,7 @@ class BaseSpatialField(Field): geometry or raster value properly and preserves any other lookup parameters. """ - value = super(BaseSpatialField, self).get_prep_value(value) + value = super().get_prep_value(value) # For IsValid lookups, boolean values are allowed. if isinstance(value, (Expression, bool)): @@ -292,10 +292,10 @@ class GeometryField(GeoSelectFormatMixin, BaseSpatialField): self._extent = kwargs.pop('extent', (-180.0, -90.0, 180.0, 90.0)) self._tolerance = kwargs.pop('tolerance', 0.05) - super(GeometryField, self).__init__(verbose_name=verbose_name, **kwargs) + super().__init__(verbose_name=verbose_name, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(GeometryField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() # Include kwargs if they're not the default values. if self.dim != 2: kwargs['dim'] = self.dim @@ -314,7 +314,7 @@ class GeometryField(GeoSelectFormatMixin, BaseSpatialField): def get_db_prep_value(self, value, connection, *args, **kwargs): return connection.ops.Adapter( - super(GeometryField, self).get_db_prep_value(value, connection, *args, **kwargs), + super().get_db_prep_value(value, connection, *args, **kwargs), **({'geography': True} if self.geography else {}) ) @@ -329,7 +329,7 @@ class GeometryField(GeoSelectFormatMixin, BaseSpatialField): # ### Routines overloaded from Field ### def contribute_to_class(self, cls, name, **kwargs): - super(GeometryField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) # Setup for lazy-instantiated Geometry object. setattr(cls, self.attname, SpatialProxy(Geometry, self)) @@ -343,7 +343,7 @@ class GeometryField(GeoSelectFormatMixin, BaseSpatialField): if (self.dim > 2 and 'widget' not in kwargs and not getattr(defaults['form_class'].widget, 'supports_3d', False)): defaults['widget'] = forms.Textarea - return super(GeometryField, self).formfield(**defaults) + return super().formfield(**defaults) # The OpenGIS Geometry Type Fields @@ -414,7 +414,7 @@ class RasterField(BaseSpatialField): def db_type(self, connection): self._check_connection(connection) - return super(RasterField, self).db_type(connection) + return super().db_type(connection) def from_db_value(self, value, expression, connection, context): return connection.ops.parse_raster(value) @@ -424,10 +424,10 @@ class RasterField(BaseSpatialField): # Prepare raster for writing to database. if not prepared: value = connection.ops.deconstruct_raster(value) - return super(RasterField, self).get_db_prep_value(value, connection, prepared) + return super().get_db_prep_value(value, connection, prepared) def contribute_to_class(self, cls, name, **kwargs): - super(RasterField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) # Setup for lazy-instantiated Raster object. For large querysets, the # instantiation of all GDALRasters can potentially be expensive. This # delays the instantiation of the objects to the moment of evaluation @@ -444,4 +444,4 @@ class RasterField(BaseSpatialField): ) except ValueError: pass - return super(RasterField, self).get_transform(name) + return super().get_transform(name) diff --git a/django/contrib/gis/db/models/functions.py b/django/contrib/gis/db/models/functions.py index 5454b2a740..01b2c93446 100644 --- a/django/contrib/gis/db/models/functions.py +++ b/django/contrib/gis/db/models/functions.py @@ -21,7 +21,7 @@ class GeoFunc(Func): def __init__(self, *expressions, **extra): if 'output_field' not in extra and self.output_field_class: extra['output_field'] = self.output_field_class() - super(GeoFunc, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) @property def name(self): @@ -46,10 +46,10 @@ class GeoFunc(Func): self.function = connection.ops.spatial_function_name(self.name) if any(isinstance(field, RasterField) for field in self.get_source_fields()): raise TypeError("Geometry functions not supported for raster fields.") - return super(GeoFunc, self).as_sql(compiler, connection, **extra_context) + return super().as_sql(compiler, connection, **extra_context) def resolve_expression(self, *args, **kwargs): - res = super(GeoFunc, self).resolve_expression(*args, **kwargs) + res = super().resolve_expression(*args, **kwargs) base_srid = res.srid if not base_srid: raise TypeError("Geometry functions can only operate on geometric content.") @@ -88,7 +88,7 @@ class GeomValue(Value): self.value = connection.ops.Adapter(self.value, geography=self.geography) else: self.value = connection.ops.Adapter(self.value) - return super(GeomValue, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class GeoFuncWithGeoParam(GeoFunc): @@ -97,7 +97,7 @@ class GeoFuncWithGeoParam(GeoFunc): raise TypeError("Please provide a geometry object.") if not hasattr(geom, 'srid') or not geom.srid: raise ValueError("Please provide a geometry attribute with a defined SRID.") - super(GeoFuncWithGeoParam, self).__init__(expression, GeomValue(geom), *expressions, **extra) + super().__init__(expression, GeomValue(geom), *expressions, **extra) class SQLiteDecimalToFloatMixin: @@ -109,7 +109,7 @@ class SQLiteDecimalToFloatMixin: for expr in self.get_source_expressions(): if hasattr(expr, 'value') and isinstance(expr.value, Decimal): expr.value = float(expr.value) - return super(SQLiteDecimalToFloatMixin, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class OracleToleranceMixin: @@ -118,7 +118,7 @@ class OracleToleranceMixin: def as_oracle(self, compiler, connection): tol = self.extra.get('tolerance', self.tolerance) self.template = "%%(function)s(%%(expressions)s, %s)" % tol - return super(OracleToleranceMixin, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class Area(OracleToleranceMixin, GeoFunc): @@ -141,11 +141,11 @@ class Area(OracleToleranceMixin, GeoFunc): units_name = geo_field.units_name(connection) if units_name: self.output_field.area_att = AreaMeasure.unit_attname(units_name) - return super(Area, self).as_sql(compiler, connection, **extra_context) + return super().as_sql(compiler, connection, **extra_context) def as_oracle(self, compiler, connection): self.output_field = AreaField('sq_m') # Oracle returns area in units of meters. - return super(Area, self).as_oracle(compiler, connection) + return super().as_oracle(compiler, connection) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): @@ -170,7 +170,7 @@ class AsGeoJSON(GeoFunc): options = 2 if options: expressions.append(options) - super(AsGeoJSON, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) class AsGML(GeoFunc): @@ -181,7 +181,7 @@ class AsGML(GeoFunc): expressions = [version, expression] if precision is not None: expressions.append(self._handle_param(precision, 'precision', int)) - super(AsGML, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) def as_oracle(self, compiler, connection, **extra_context): source_expressions = self.get_source_expressions() @@ -196,7 +196,7 @@ class AsKML(AsGML): def as_sqlite(self, compiler, connection): # No version parameter self.source_expressions.pop(0) - return super(AsKML, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class AsSVG(GeoFunc): @@ -209,12 +209,12 @@ class AsSVG(GeoFunc): relative, self._handle_param(precision, 'precision', int), ] - super(AsSVG, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) class BoundingCircle(OracleToleranceMixin, GeoFunc): def __init__(self, expression, num_seg=48, **extra): - super(BoundingCircle, self).__init__(*[expression, num_seg], **extra) + super().__init__(*[expression, num_seg], **extra) def as_oracle(self, compiler, connection): clone = self.copy() @@ -260,7 +260,7 @@ class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFuncWithGeoParam): if spheroid is not None: self.spheroid = spheroid expressions += (self._handle_param(spheroid, 'spheroid', bool),) - super(Distance, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) def as_postgresql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info @@ -279,12 +279,12 @@ class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFuncWithGeoParam): self.source_expressions[2] = Value(geo_field._spheroid) else: self.function = connection.ops.spatial_function_name('DistanceSphere') - return super(Distance, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) def as_oracle(self, compiler, connection): if self.spheroid: self.source_expressions.pop(2) - return super(Distance, self).as_oracle(compiler, connection) + return super().as_oracle(compiler, connection) def as_sqlite(self, compiler, connection, **extra_context): if self.spheroid: @@ -293,7 +293,7 @@ class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFuncWithGeoParam): # SpatiaLite returns NULL instead of zero on geodetic coordinates extra_context['template'] = 'COALESCE(%(function)s(%(expressions)s, %(spheroid)s), 0)' extra_context['spheroid'] = int(bool(self.spheroid)) - return super(Distance, self).as_sql(compiler, connection, **extra_context) + return super().as_sql(compiler, connection, **extra_context) class Envelope(GeoFunc): @@ -311,7 +311,7 @@ class GeoHash(GeoFunc): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, 'precision', int)) - super(GeoHash, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) class Intersection(OracleToleranceMixin, GeoFuncWithGeoParam): @@ -322,7 +322,7 @@ class IsValid(OracleToleranceMixin, GeoFunc): output_field_class = BooleanField def as_oracle(self, compiler, connection, **extra_context): - sql, params = super(IsValid, self).as_oracle(compiler, connection, **extra_context) + sql, params = super().as_oracle(compiler, connection, **extra_context) return "CASE %s WHEN 'TRUE' THEN 1 ELSE 0 END" % sql, params @@ -331,13 +331,13 @@ class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): def __init__(self, expr1, spheroid=True, **extra): self.spheroid = spheroid - super(Length, self).__init__(expr1, **extra) + super().__init__(expr1, **extra) def as_sql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if geo_field.geodetic(connection) and not connection.features.supports_length_geodetic: raise NotImplementedError("This backend doesn't support Length on geodetic fields") - return super(Length, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) def as_postgresql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info @@ -351,7 +351,7 @@ class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): dim = min(f.dim for f in self.get_source_fields() if f) if dim > 2: self.function = connection.ops.length3d - return super(Length, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) def as_sqlite(self, compiler, connection): geo_field = GeometryField(srid=self.srid) @@ -360,7 +360,7 @@ class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): self.function = 'GeodesicLength' else: self.function = 'GreatCircleLength' - return super(Length, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class MakeValid(GeoFunc): @@ -385,7 +385,7 @@ class NumPoints(GeoFunc): if self.source_expressions[self.geom_param_pos].output_field.geom_type != 'LINESTRING': if not connection.features.supports_num_points_poly: raise TypeError('NumPoints can only operate on LineString content on this database.') - return super(NumPoints, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc): @@ -399,13 +399,13 @@ class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc): dim = min(f.dim for f in self.get_source_fields()) if dim > 2: self.function = connection.ops.perimeter3d - return super(Perimeter, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) def as_sqlite(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if geo_field.geodetic(connection): raise NotImplementedError("Perimeter cannot use a non-projected field.") - return super(Perimeter, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class PointOnSurface(OracleToleranceMixin, GeoFunc): @@ -425,7 +425,7 @@ class Scale(SQLiteDecimalToFloatMixin, GeoFunc): ] if z != 0.0: expressions.append(self._handle_param(z, 'z', NUMERIC_TYPES)) - super(Scale, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) class SnapToGrid(SQLiteDecimalToFloatMixin, GeoFunc): @@ -446,7 +446,7 @@ class SnapToGrid(SQLiteDecimalToFloatMixin, GeoFunc): ) else: raise ValueError('Must provide 1, 2, or 4 arguments to `SnapToGrid`.') - super(SnapToGrid, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) class SymDifference(OracleToleranceMixin, GeoFuncWithGeoParam): @@ -461,7 +461,7 @@ class Transform(GeoFunc): ] if 'output_field' not in extra: extra['output_field'] = GeometryField(srid=srid) - super(Transform, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) @property def srid(self): @@ -474,7 +474,7 @@ class Translate(Scale): if len(self.source_expressions) < 4: # Always provide the z parameter for ST_Translate self.source_expressions.append(Value(0)) - return super(Translate, self).as_sqlite(compiler, connection) + return super().as_sqlite(compiler, connection) class Union(OracleToleranceMixin, GeoFuncWithGeoParam): diff --git a/django/contrib/gis/db/models/lookups.py b/django/contrib/gis/db/models/lookups.py index 3b2d4b8497..ada5890872 100644 --- a/django/contrib/gis/db/models/lookups.py +++ b/django/contrib/gis/db/models/lookups.py @@ -22,7 +22,7 @@ class GISLookup(Lookup): band_lhs = None def __init__(self, *args, **kwargs): - super(GISLookup, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.template_params = {} @classmethod @@ -100,7 +100,7 @@ class GISLookup(Lookup): def process_rhs(self, compiler, connection): if isinstance(self.rhs, Query): # If rhs is some Query, don't touch it. - return super(GISLookup, self).process_rhs(compiler, connection) + return super().process_rhs(compiler, connection) geom = self.rhs if isinstance(self.rhs, Col): @@ -124,7 +124,7 @@ class GISLookup(Lookup): elif isinstance(self.lhs, RasterBandTransform): self.process_band_indices(only_lhs=True) - rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection) + rhs, rhs_params = super().process_rhs(compiler, connection) rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler) return rhs, rhs_params @@ -390,7 +390,7 @@ class RelateLookup(GISLookup): pattern = value[1] if not isinstance(pattern, str) or not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) - return super(RelateLookup, self).get_db_prep_lookup(value, connection) + return super().get_db_prep_lookup(value, connection) gis_lookups['relate'] = RelateLookup diff --git a/django/contrib/gis/db/models/proxy.py b/django/contrib/gis/db/models/proxy.py index 86221daca7..8f6a8a602d 100644 --- a/django/contrib/gis/db/models/proxy.py +++ b/django/contrib/gis/db/models/proxy.py @@ -16,7 +16,7 @@ class SpatialProxy(DeferredAttribute): """ self._field = field self._klass = klass - super(SpatialProxy, self).__init__(field.attname, klass) + super().__init__(field.attname, klass) def __get__(self, instance, cls=None): """ @@ -33,7 +33,7 @@ class SpatialProxy(DeferredAttribute): try: geo_value = instance.__dict__[self._field.attname] except KeyError: - geo_value = super(SpatialProxy, self).__get__(instance, cls) + geo_value = super().__get__(instance, cls) if isinstance(geo_value, self._klass): geo_obj = geo_value diff --git a/django/contrib/gis/feeds.py b/django/contrib/gis/feeds.py index 807a313bf4..b98e59653a 100644 --- a/django/contrib/gis/feeds.py +++ b/django/contrib/gis/feeds.py @@ -82,46 +82,46 @@ class GeoFeedMixin: # ### SyndicationFeed subclasses ### class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): - attrs = super(GeoRSSFeed, self).rss_attributes() + attrs = super().rss_attributes() attrs['xmlns:georss'] = 'http://www.georss.org/georss' return attrs def add_item_elements(self, handler, item): - super(GeoRSSFeed, self).add_item_elements(handler, item) + super().add_item_elements(handler, item) self.add_georss_element(handler, item) def add_root_elements(self, handler): - super(GeoRSSFeed, self).add_root_elements(handler) + super().add_root_elements(handler) self.add_georss_element(handler, self.feed) class GeoAtom1Feed(Atom1Feed, GeoFeedMixin): def root_attributes(self): - attrs = super(GeoAtom1Feed, self).root_attributes() + attrs = super().root_attributes() attrs['xmlns:georss'] = 'http://www.georss.org/georss' return attrs def add_item_elements(self, handler, item): - super(GeoAtom1Feed, self).add_item_elements(handler, item) + super().add_item_elements(handler, item) self.add_georss_element(handler, item) def add_root_elements(self, handler): - super(GeoAtom1Feed, self).add_root_elements(handler) + super().add_root_elements(handler) self.add_georss_element(handler, self.feed) class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin): def rss_attributes(self): - attrs = super(W3CGeoFeed, self).rss_attributes() + attrs = super().rss_attributes() attrs['xmlns:geo'] = 'http://www.w3.org/2003/01/geo/wgs84_pos#' return attrs def add_item_elements(self, handler, item): - super(W3CGeoFeed, self).add_item_elements(handler, item) + super().add_item_elements(handler, item) self.add_georss_element(handler, item, w3c_geo=True) def add_root_elements(self, handler): - super(W3CGeoFeed, self).add_root_elements(handler) + super().add_root_elements(handler) self.add_georss_element(handler, self.feed, w3c_geo=True) diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py index ef0f4a9bee..f435bd5ab1 100644 --- a/django/contrib/gis/forms/fields.py +++ b/django/contrib/gis/forms/fields.py @@ -27,7 +27,7 @@ class GeometryField(forms.Field): # defaults (e.g., allow None). self.srid = kwargs.pop('srid', None) self.geom_type = kwargs.pop('geom_type', self.geom_type) - super(GeometryField, self).__init__(**kwargs) + super().__init__(**kwargs) self.widget.attrs['geom_type'] = self.geom_type def to_python(self, value): @@ -58,7 +58,7 @@ class GeometryField(forms.Field): object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry. """ - geom = super(GeometryField, self).clean(value) + geom = super().clean(value) if geom is None: return geom diff --git a/django/contrib/gis/forms/widgets.py b/django/contrib/gis/forms/widgets.py index 0c1fc23c81..0ec98a3f4a 100644 --- a/django/contrib/gis/forms/widgets.py +++ b/django/contrib/gis/forms/widgets.py @@ -103,7 +103,7 @@ class OSMWidget(OpenLayersWidget): map_srid = 3857 def __init__(self, attrs=None): - super(OSMWidget, self).__init__() + super().__init__() for key in ('default_lon', 'default_lat'): self.attrs[key] = getattr(self, key) if attrs: diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py index b1acc5bf5b..4b4f336071 100644 --- a/django/contrib/gis/gdal/geometries.py +++ b/django/contrib/gis/gdal/geometries.py @@ -502,7 +502,7 @@ class Point(OGRGeometry): def _geos_ptr(self): from django.contrib.gis import geos - return geos.Point._create_empty() if self.empty else super(Point, self)._geos_ptr() + return geos.Point._create_empty() if self.empty else super()._geos_ptr() @classmethod def _create_empty(cls): diff --git a/django/contrib/gis/geos/collections.py b/django/contrib/gis/geos/collections.py index e964a1de8f..a3b0e74faa 100644 --- a/django/contrib/gis/geos/collections.py +++ b/django/contrib/gis/geos/collections.py @@ -37,7 +37,7 @@ class GeometryCollection(GEOSGeometry): # Creating the geometry pointer array. collection = self._create_collection(len(init_geoms), iter(init_geoms)) - super(GeometryCollection, self).__init__(collection, **kwargs) + super().__init__(collection, **kwargs) def __iter__(self): "Iterates over each Geometry in the Collection." @@ -89,7 +89,7 @@ class GeometryCollection(GEOSGeometry): for geom in self ], }) - return super(GeometryCollection, self).json + return super().json geojson = json @property @@ -118,7 +118,7 @@ class MultiLineString(LinearGeometryMixin, GeometryCollection): def closed(self): if geos_version_info()['version'] < '3.5': raise GEOSException("MultiLineString.closed requires GEOS >= 3.5.0.") - return super(MultiLineString, self).closed + return super().closed class MultiPolygon(GeometryCollection): diff --git a/django/contrib/gis/geos/io.py b/django/contrib/gis/geos/io.py index daf67dd28c..11abe10e3d 100644 --- a/django/contrib/gis/geos/io.py +++ b/django/contrib/gis/geos/io.py @@ -15,10 +15,10 @@ __all__ = ['WKBWriter', 'WKTWriter', 'WKBReader', 'WKTReader'] class WKBReader(_WKBReader): def read(self, wkb): "Returns a GEOSGeometry for the given WKB buffer." - return GEOSGeometry(super(WKBReader, self).read(wkb)) + return GEOSGeometry(super().read(wkb)) class WKTReader(_WKTReader): def read(self, wkt): "Returns a GEOSGeometry for the given WKT string." - return GEOSGeometry(super(WKTReader, self).read(wkt)) + return GEOSGeometry(super().read(wkt)) diff --git a/django/contrib/gis/geos/linestring.py b/django/contrib/gis/geos/linestring.py index 6caf6bef34..667c2da379 100644 --- a/django/contrib/gis/geos/linestring.py +++ b/django/contrib/gis/geos/linestring.py @@ -37,7 +37,7 @@ class LineString(LinearGeometryMixin, GEOSGeometry): ncoords = len(coords) if not ncoords: - super(LineString, self).__init__(self._init_func(None), srid=srid) + super().__init__(self._init_func(None), srid=srid) return if ncoords < self._minlength: @@ -86,7 +86,7 @@ class LineString(LinearGeometryMixin, GEOSGeometry): # Calling the base geometry initialization with the returned pointer # from the function. - super(LineString, self).__init__(self._init_func(cs.ptr), srid=srid) + super().__init__(self._init_func(cs.ptr), srid=srid) def __iter__(self): "Allows iteration over this LineString." diff --git a/django/contrib/gis/geos/mutable_list.py b/django/contrib/gis/geos/mutable_list.py index c7fb703ce1..fa5faccd1e 100644 --- a/django/contrib/gis/geos/mutable_list.py +++ b/django/contrib/gis/geos/mutable_list.py @@ -67,7 +67,7 @@ class ListMixin: self._set_single = self._set_single_rebuild self._assign_extended_slice = self._assign_extended_slice_rebuild - super(ListMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __getitem__(self, index): "Get the item(s) at the specified index/slice." diff --git a/django/contrib/gis/geos/point.py b/django/contrib/gis/geos/point.py index 6486b2a5e1..aeb6303e39 100644 --- a/django/contrib/gis/geos/point.py +++ b/django/contrib/gis/geos/point.py @@ -38,10 +38,10 @@ class Point(GEOSGeometry): # Initializing using the address returned from the GEOS # createPoint factory. - super(Point, self).__init__(point, srid=srid) + super().__init__(point, srid=srid) def _ogr_ptr(self): - return gdal.geometries.Point._create_empty() if self.empty else super(Point, self)._ogr_ptr() + return gdal.geometries.Point._create_empty() if self.empty else super()._ogr_ptr() @classmethod def _create_empty(cls): diff --git a/django/contrib/gis/geos/polygon.py b/django/contrib/gis/geos/polygon.py index 58f1b28c29..42d351a84f 100644 --- a/django/contrib/gis/geos/polygon.py +++ b/django/contrib/gis/geos/polygon.py @@ -27,7 +27,7 @@ class Polygon(GEOSGeometry): ... ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4))) """ if not args: - super(Polygon, self).__init__(self._create_polygon(0, None), **kwargs) + super().__init__(self._create_polygon(0, None), **kwargs) return # Getting the ext_ring and init_holes parameters from the argument list @@ -45,7 +45,7 @@ class Polygon(GEOSGeometry): n_holes = len(init_holes) polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes) - super(Polygon, self).__init__(polygon, **kwargs) + super().__init__(polygon, **kwargs) def __iter__(self): "Iterates over each ring in the polygon." diff --git a/django/contrib/gis/geos/prototypes/coordseq.py b/django/contrib/gis/geos/prototypes/coordseq.py index 982ce32613..a21c64946d 100644 --- a/django/contrib/gis/geos/prototypes/coordseq.py +++ b/django/contrib/gis/geos/prototypes/coordseq.py @@ -48,7 +48,7 @@ class CsOperation(GEOSFuncFactory): self.argtypes = [CS_PTR, c_uint, c_uint, dbl_param] else: self.argtypes = [CS_PTR, c_uint, dbl_param] - return super(CsOperation, self).get_func() + return super().get_func() class CsOutput(GEOSFuncFactory): @@ -56,7 +56,7 @@ class CsOutput(GEOSFuncFactory): def get_func(self, argtypes): self.argtypes = argtypes - return super(CsOutput, self).get_func() + return super().get_func() @staticmethod def errcheck(result, func, cargs): diff --git a/django/contrib/gis/geos/prototypes/geom.py b/django/contrib/gis/geos/prototypes/geom.py index 9e14f214dc..cb6aa2c9a1 100644 --- a/django/contrib/gis/geos/prototypes/geom.py +++ b/django/contrib/gis/geos/prototypes/geom.py @@ -43,7 +43,7 @@ class GeomOutput(GEOSFuncFactory): def get_func(self, argtypes): self.argtypes = argtypes - return super(GeomOutput, self).get_func() + return super().get_func() class IntFromGeom(GEOSFuncFactory): @@ -56,7 +56,7 @@ class IntFromGeom(GEOSFuncFactory): self.errcheck = check_zero else: self.errcheck = check_minus_one - return super(IntFromGeom, self).get_func() + return super().get_func() class StringFromGeom(GEOSFuncFactory): diff --git a/django/contrib/gis/geos/prototypes/io.py b/django/contrib/gis/geos/prototypes/io.py index b8b1a06dba..8cbc3c560d 100644 --- a/django/contrib/gis/geos/prototypes/io.py +++ b/django/contrib/gis/geos/prototypes/io.py @@ -165,7 +165,7 @@ class WKTWriter(IOBase): _precision = None def __init__(self, dim=2, trim=False, precision=None): - super(WKTWriter, self).__init__() + super().__init__() if bool(trim) != self._trim: self.trim = trim if precision is not None: @@ -215,7 +215,7 @@ class WKBWriter(IOBase): destructor = wkb_writer_destroy def __init__(self, dim=2): - super(WKBWriter, self).__init__() + super().__init__() self.outdim = dim def _handle_empty_point(self, geom): diff --git a/django/contrib/gis/geos/prototypes/misc.py b/django/contrib/gis/geos/prototypes/misc.py index 2d890c3d31..1f809ebe70 100644 --- a/django/contrib/gis/geos/prototypes/misc.py +++ b/django/contrib/gis/geos/prototypes/misc.py @@ -23,7 +23,7 @@ class DblFromGeom(GEOSFuncFactory): argtypes = [GEOM_PTR for i in range(num_geom)] argtypes += [POINTER(c_double)] self.argtypes = argtypes - return super(DblFromGeom, self).get_func() + return super().get_func() # ### ctypes prototypes ### diff --git a/django/contrib/gis/management/commands/inspectdb.py b/django/contrib/gis/management/commands/inspectdb.py index 27345c59d4..012ca14fed 100644 --- a/django/contrib/gis/management/commands/inspectdb.py +++ b/django/contrib/gis/management/commands/inspectdb.py @@ -6,7 +6,7 @@ class Command(InspectDBCommand): db_module = 'django.contrib.gis.db' def get_field_type(self, connection, table_name, row): - field_type, field_params, field_notes = super(Command, self).get_field_type(connection, table_name, row) + field_type, field_params, field_notes = super().get_field_type(connection, table_name, row) if field_type == 'GeometryField': geo_col = row[0] # Getting a more specific field type and any additional parameters diff --git a/django/contrib/gis/serializers/geojson.py b/django/contrib/gis/serializers/geojson.py index 3a4c0c87bf..fe3a32871f 100644 --- a/django/contrib/gis/serializers/geojson.py +++ b/django/contrib/gis/serializers/geojson.py @@ -11,7 +11,7 @@ class Serializer(JSONSerializer): Convert a queryset to GeoJSON, http://geojson.org/ """ def _init_options(self): - super(Serializer, self)._init_options() + super()._init_options() self.geometry_field = self.json_kwargs.pop('geometry_field', None) self.srid = self.json_kwargs.pop('srid', 4326) if (self.selected_fields is not None and self.geometry_field is not None and @@ -29,7 +29,7 @@ class Serializer(JSONSerializer): self.stream.write(']}') def start_object(self, obj): - super(Serializer, self).start_object(obj) + super().start_object(obj) self._geometry = None if self.geometry_field is None: # Find the first declared geometry field @@ -62,7 +62,7 @@ class Serializer(JSONSerializer): if field.name == self.geometry_field: self._geometry = field.value_from_object(obj) else: - super(Serializer, self).handle_field(obj, field) + super().handle_field(obj, field) class Deserializer: diff --git a/django/contrib/messages/storage/base.py b/django/contrib/messages/storage/base.py index 28c81599a7..2e67c84f4a 100644 --- a/django/contrib/messages/storage/base.py +++ b/django/contrib/messages/storage/base.py @@ -64,7 +64,7 @@ class BaseStorage: self._queued_messages = [] self.used = False self.added_new = False - super(BaseStorage, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __len__(self): return len(self._loaded_messages) + len(self._queued_messages) diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py index b8d7f7474c..353dc12761 100644 --- a/django/contrib/messages/storage/cookie.py +++ b/django/contrib/messages/storage/cookie.py @@ -21,7 +21,7 @@ class MessageEncoder(json.JSONEncoder): if obj.extra_tags: message.append(obj.extra_tags) return message - return super(MessageEncoder, self).default(obj) + return super().default(obj) class MessageDecoder(json.JSONDecoder): @@ -45,7 +45,7 @@ class MessageDecoder(json.JSONDecoder): return obj def decode(self, s, **kwargs): - decoded = super(MessageDecoder, self).decode(s, **kwargs) + decoded = super().decode(s, **kwargs) return self.process_messages(decoded) diff --git a/django/contrib/messages/storage/fallback.py b/django/contrib/messages/storage/fallback.py index 24dd6561d0..d599833dc1 100644 --- a/django/contrib/messages/storage/fallback.py +++ b/django/contrib/messages/storage/fallback.py @@ -11,7 +11,7 @@ class FallbackStorage(BaseStorage): storage_classes = (CookieStorage, SessionStorage) def __init__(self, *args, **kwargs): - super(FallbackStorage, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.storages = [storage_class(*args, **kwargs) for storage_class in self.storage_classes] self._used_storages = set() diff --git a/django/contrib/messages/storage/session.py b/django/contrib/messages/storage/session.py index 2eb8024bfa..ca859a35a0 100644 --- a/django/contrib/messages/storage/session.py +++ b/django/contrib/messages/storage/session.py @@ -18,7 +18,7 @@ class SessionStorage(BaseStorage): "message storage requires session middleware to be installed, "\ "and come before the message middleware in the "\ "MIDDLEWARE%s list." % ("_CLASSES" if settings.MIDDLEWARE is None else "") - super(SessionStorage, self).__init__(request, *args, **kwargs) + super().__init__(request, *args, **kwargs) def _get(self, *args, **kwargs): """ diff --git a/django/contrib/messages/views.py b/django/contrib/messages/views.py index adb3f194b9..246340edb2 100644 --- a/django/contrib/messages/views.py +++ b/django/contrib/messages/views.py @@ -8,7 +8,7 @@ class SuccessMessageMixin: success_message = '' def form_valid(self, form): - response = super(SuccessMessageMixin, self).form_valid(form) + response = super().form_valid(form) success_message = self.get_success_message(form.cleaned_data) if success_message: messages.success(self.request, success_message) diff --git a/django/contrib/postgres/aggregates/general.py b/django/contrib/postgres/aggregates/general.py index 5b3d22bf98..ac18a516d6 100644 --- a/django/contrib/postgres/aggregates/general.py +++ b/django/contrib/postgres/aggregates/general.py @@ -47,7 +47,7 @@ class StringAgg(Aggregate): def __init__(self, expression, delimiter, distinct=False, **extra): distinct = 'DISTINCT ' if distinct else '' - super(StringAgg, self).__init__(expression, delimiter=delimiter, distinct=distinct, **extra) + super().__init__(expression, delimiter=delimiter, distinct=distinct, **extra) def convert_value(self, value, expression, connection, context): if not value: diff --git a/django/contrib/postgres/aggregates/statistics.py b/django/contrib/postgres/aggregates/statistics.py index 89949580be..2af5b6b359 100644 --- a/django/contrib/postgres/aggregates/statistics.py +++ b/django/contrib/postgres/aggregates/statistics.py @@ -11,7 +11,7 @@ class StatAggregate(Aggregate): def __init__(self, y, x, output_field=FloatField()): if not x or not y: raise ValueError('Both y and x must be provided.') - super(StatAggregate, self).__init__(y=y, x=x, output_field=output_field) + super().__init__(y=y, x=x, output_field=output_field) self.x = x self.y = y self.source_expressions = self._parse_expressions(self.y, self.x) @@ -23,7 +23,7 @@ class StatAggregate(Aggregate): self.y, self.x = exprs def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - return super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize) + return super().resolve_expression(query, allow_joins, reuse, summarize) class Corr(StatAggregate): @@ -33,7 +33,7 @@ class Corr(StatAggregate): class CovarPop(StatAggregate): def __init__(self, y, x, sample=False): self.function = 'COVAR_SAMP' if sample else 'COVAR_POP' - super(CovarPop, self).__init__(y, x) + super().__init__(y, x) class RegrAvgX(StatAggregate): @@ -48,7 +48,7 @@ class RegrCount(StatAggregate): function = 'REGR_COUNT' def __init__(self, y, x): - super(RegrCount, self).__init__(y=y, x=x, output_field=IntegerField()) + super().__init__(y=y, x=x, output_field=IntegerField()) def convert_value(self, value, expression, connection, context): if value is None: diff --git a/django/contrib/postgres/fields/array.py b/django/contrib/postgres/fields/array.py index ce4c7b8c3d..15cbf5e45e 100644 --- a/django/contrib/postgres/fields/array.py +++ b/django/contrib/postgres/fields/array.py @@ -31,7 +31,7 @@ class ArrayField(Field): # implements it. if hasattr(self.base_field, 'from_db_value'): self.from_db_value = self._from_db_value - super(ArrayField, self).__init__(**kwargs) + super().__init__(**kwargs) @property def model(self): @@ -46,7 +46,7 @@ class ArrayField(Field): self.base_field.model = model def check(self, **kwargs): - errors = super(ArrayField, self).check(**kwargs) + errors = super().check(**kwargs) if self.base_field.remote_field: errors.append( checks.Error( @@ -70,7 +70,7 @@ class ArrayField(Field): return errors def set_attributes_from_name(self, name): - super(ArrayField, self).set_attributes_from_name(name) + super().set_attributes_from_name(name) self.base_field.set_attributes_from_name(name) @property @@ -87,7 +87,7 @@ class ArrayField(Field): return value def deconstruct(self): - name, path, args, kwargs = super(ArrayField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if path == 'django.contrib.postgres.fields.array.ArrayField': path = 'django.contrib.postgres.fields.ArrayField' kwargs.update({ @@ -125,7 +125,7 @@ class ArrayField(Field): return json.dumps(values) def get_transform(self, name): - transform = super(ArrayField, self).get_transform(name) + transform = super().get_transform(name) if transform: return transform if '_' not in name: @@ -146,7 +146,7 @@ class ArrayField(Field): return SliceTransformFactory(start, end) def validate(self, value, model_instance): - super(ArrayField, self).validate(value, model_instance) + super().validate(value, model_instance) for index, part in enumerate(value): try: self.base_field.validate(part, model_instance) @@ -165,7 +165,7 @@ class ArrayField(Field): ) def run_validators(self, value): - super(ArrayField, self).run_validators(value) + super().run_validators(value) for index, part in enumerate(value): try: self.base_field.run_validators(part) @@ -184,13 +184,13 @@ class ArrayField(Field): 'max_length': self.size, } defaults.update(kwargs) - return super(ArrayField, self).formfield(**defaults) + return super().formfield(**defaults) @ArrayField.register_lookup class ArrayContains(lookups.DataContains): def as_sql(self, qn, connection): - sql, params = super(ArrayContains, self).as_sql(qn, connection) + sql, params = super().as_sql(qn, connection) sql = '%s::%s' % (sql, self.lhs.output_field.db_type(connection)) return sql, params @@ -198,7 +198,7 @@ class ArrayContains(lookups.DataContains): @ArrayField.register_lookup class ArrayContainedBy(lookups.ContainedBy): def as_sql(self, qn, connection): - sql, params = super(ArrayContainedBy, self).as_sql(qn, connection) + sql, params = super().as_sql(qn, connection) sql = '%s::%s' % (sql, self.lhs.output_field.db_type(connection)) return sql, params @@ -206,7 +206,7 @@ class ArrayContainedBy(lookups.ContainedBy): @ArrayField.register_lookup class ArrayExact(Exact): def as_sql(self, qn, connection): - sql, params = super(ArrayExact, self).as_sql(qn, connection) + sql, params = super().as_sql(qn, connection) sql = '%s::%s' % (sql, self.lhs.output_field.db_type(connection)) return sql, params @@ -214,7 +214,7 @@ class ArrayExact(Exact): @ArrayField.register_lookup class ArrayOverlap(lookups.Overlap): def as_sql(self, qn, connection): - sql, params = super(ArrayOverlap, self).as_sql(qn, connection) + sql, params = super().as_sql(qn, connection) sql = '%s::%s' % (sql, self.lhs.output_field.db_type(connection)) return sql, params @@ -236,7 +236,7 @@ class ArrayLenTransform(Transform): @ArrayField.register_lookup class ArrayInLookup(In): def get_prep_lookup(self): - values = super(ArrayInLookup, self).get_prep_lookup() + values = super().get_prep_lookup() # In.process_rhs() expects values to be hashable, so convert lists # to tuples. prepared_values = [] @@ -251,7 +251,7 @@ class ArrayInLookup(In): class IndexTransform(Transform): def __init__(self, index, base_field, *args, **kwargs): - super(IndexTransform, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.index = index self.base_field = base_field @@ -277,7 +277,7 @@ class IndexTransformFactory: class SliceTransform(Transform): def __init__(self, start, end, *args, **kwargs): - super(SliceTransform, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.start = start self.end = end diff --git a/django/contrib/postgres/fields/hstore.py b/django/contrib/postgres/fields/hstore.py index 5e2e6c3155..28b7c19c7d 100644 --- a/django/contrib/postgres/fields/hstore.py +++ b/django/contrib/postgres/fields/hstore.py @@ -21,13 +21,13 @@ class HStoreField(Field): return 'hstore' def get_transform(self, name): - transform = super(HStoreField, self).get_transform(name) + transform = super().get_transform(name) if transform: return transform return KeyTransformFactory(name) def validate(self, value, model_instance): - super(HStoreField, self).validate(value, model_instance) + super().validate(value, model_instance) for key, val in value.items(): if not isinstance(val, str) and val is not None: raise exceptions.ValidationError( @@ -49,10 +49,10 @@ class HStoreField(Field): 'form_class': forms.HStoreField, } defaults.update(kwargs) - return super(HStoreField, self).formfield(**defaults) + return super().formfield(**defaults) def get_prep_value(self, value): - value = super(HStoreField, self).get_prep_value(value) + value = super().get_prep_value(value) if isinstance(value, dict): prep_value = {} @@ -80,7 +80,7 @@ class KeyTransform(Transform): output_field = TextField() def __init__(self, key_name, *args, **kwargs): - super(KeyTransform, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.key_name = key_name def as_sql(self, compiler, connection): diff --git a/django/contrib/postgres/fields/jsonb.py b/django/contrib/postgres/fields/jsonb.py index 43997050fe..0bb6e7bed1 100644 --- a/django/contrib/postgres/fields/jsonb.py +++ b/django/contrib/postgres/fields/jsonb.py @@ -18,7 +18,7 @@ class JsonAdapter(Json): """ def __init__(self, adapted, dumps=None, encoder=None): self.encoder = encoder - super(JsonAdapter, self).__init__(adapted, dumps=dumps) + super().__init__(adapted, dumps=dumps) def dumps(self, obj): options = {'cls': self.encoder} if self.encoder else {} @@ -36,19 +36,19 @@ class JSONField(Field): if encoder and not callable(encoder): raise ValueError("The encoder parameter must be a callable object.") self.encoder = encoder - super(JSONField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def db_type(self, connection): return 'jsonb' def deconstruct(self): - name, path, args, kwargs = super(JSONField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.encoder is not None: kwargs['encoder'] = self.encoder return name, path, args, kwargs def get_transform(self, name): - transform = super(JSONField, self).get_transform(name) + transform = super().get_transform(name) if transform: return transform return KeyTransformFactory(name) @@ -59,7 +59,7 @@ class JSONField(Field): return value def validate(self, value, model_instance): - super(JSONField, self).validate(value, model_instance) + super().validate(value, model_instance) options = {'cls': self.encoder} if self.encoder else {} try: json.dumps(value, **options) @@ -76,7 +76,7 @@ class JSONField(Field): def formfield(self, **kwargs): defaults = {'form_class': forms.JSONField} defaults.update(kwargs) - return super(JSONField, self).formfield(**defaults) + return super().formfield(**defaults) JSONField.register_lookup(lookups.DataContains) @@ -91,7 +91,7 @@ class KeyTransform(Transform): nested_operator = '#>' def __init__(self, key_name, *args, **kwargs): - super(KeyTransform, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.key_name = key_name def as_sql(self, compiler, connection): @@ -129,7 +129,7 @@ class KeyTransformTextLookupMixin: key_text_transform = KeyTextTransform( key_transform.key_name, *key_transform.source_expressions, **key_transform.extra ) - super(KeyTransformTextLookupMixin, self).__init__(key_text_transform, *args, **kwargs) + super().__init__(key_text_transform, *args, **kwargs) class KeyTransformIExact(KeyTransformTextLookupMixin, builtin_lookups.IExact): diff --git a/django/contrib/postgres/fields/ranges.py b/django/contrib/postgres/fields/ranges.py index 840417a58f..41acc8dcb2 100644 --- a/django/contrib/postgres/fields/ranges.py +++ b/django/contrib/postgres/fields/ranges.py @@ -20,7 +20,7 @@ class RangeField(models.Field): # Initializing base_field here ensures that its model matches the model for self. if hasattr(self, 'base_field'): self.base_field = self.base_field() - super(RangeField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) @property def model(self): @@ -56,7 +56,7 @@ class RangeField(models.Field): return value def set_attributes_from_name(self, name): - super(RangeField, self).set_attributes_from_name(name) + super().set_attributes_from_name(name) self.base_field.set_attributes_from_name(name) def value_to_string(self, obj): @@ -78,7 +78,7 @@ class RangeField(models.Field): def formfield(self, **kwargs): kwargs.setdefault('form_class', self.form_field) - return super(RangeField, self).formfield(**kwargs) + return super().formfield(**kwargs) class IntegerRangeField(RangeField): diff --git a/django/contrib/postgres/forms/array.py b/django/contrib/postgres/forms/array.py index 9a9e871a43..d9d864e4f2 100644 --- a/django/contrib/postgres/forms/array.py +++ b/django/contrib/postgres/forms/array.py @@ -20,7 +20,7 @@ class SimpleArrayField(forms.CharField): def __init__(self, base_field, delimiter=',', max_length=None, min_length=None, *args, **kwargs): self.base_field = base_field self.delimiter = delimiter - super(SimpleArrayField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if min_length is not None: self.min_length = min_length self.validators.append(ArrayMinLengthValidator(int(min_length))) @@ -57,7 +57,7 @@ class SimpleArrayField(forms.CharField): return values def validate(self, value): - super(SimpleArrayField, self).validate(value) + super().validate(value) errors = [] for index, item in enumerate(value): try: @@ -73,7 +73,7 @@ class SimpleArrayField(forms.CharField): raise ValidationError(errors) def run_validators(self, value): - super(SimpleArrayField, self).run_validators(value) + super().run_validators(value) errors = [] for index, item in enumerate(value): try: @@ -94,7 +94,7 @@ class SplitArrayWidget(forms.Widget): def __init__(self, widget, size, **kwargs): self.widget = widget() if isinstance(widget, type) else widget self.size = size - super(SplitArrayWidget, self).__init__(**kwargs) + super().__init__(**kwargs) @property def is_hidden(self): @@ -141,7 +141,7 @@ class SplitArrayWidget(forms.Widget): return self.widget.media def __deepcopy__(self, memo): - obj = super(SplitArrayWidget, self).__deepcopy__(memo) + obj = super().__deepcopy__(memo) obj.widget = copy.deepcopy(self.widget) return obj @@ -161,7 +161,7 @@ class SplitArrayField(forms.Field): self.remove_trailing_nulls = remove_trailing_nulls widget = SplitArrayWidget(widget=base_field.widget, size=size) kwargs.setdefault('widget', widget) - super(SplitArrayField, self).__init__(**kwargs) + super().__init__(**kwargs) def clean(self, value): cleaned_data = [] diff --git a/django/contrib/postgres/forms/hstore.py b/django/contrib/postgres/forms/hstore.py index 25dceb9fb0..7e046ead37 100644 --- a/django/contrib/postgres/forms/hstore.py +++ b/django/contrib/postgres/forms/hstore.py @@ -55,4 +55,4 @@ class HStoreField(forms.CharField): # the same as an empty dict, if the data or initial value we get # is None, replace it w/ {}. initial_value = self.to_python(initial) - return super(HStoreField, self).has_changed(initial_value, data) + return super().has_changed(initial_value, data) diff --git a/django/contrib/postgres/forms/ranges.py b/django/contrib/postgres/forms/ranges.py index 9ed95cd7c5..5be166f7d0 100644 --- a/django/contrib/postgres/forms/ranges.py +++ b/django/contrib/postgres/forms/ranges.py @@ -21,7 +21,7 @@ class BaseRangeField(forms.MultiValueField): kwargs['fields'] = [self.base_field(required=False), self.base_field(required=False)] kwargs.setdefault('required', False) kwargs.setdefault('require_all_fields', False) - super(BaseRangeField, self).__init__(**kwargs) + super().__init__(**kwargs) def prepare_value(self, value): lower_base, upper_base = self.fields @@ -84,7 +84,7 @@ class DateRangeField(BaseRangeField): class RangeWidget(MultiWidget): def __init__(self, base_widget, attrs=None): widgets = (base_widget, base_widget) - super(RangeWidget, self).__init__(widgets, attrs) + super().__init__(widgets, attrs) def decompress(self, value): if value: diff --git a/django/contrib/postgres/functions.py b/django/contrib/postgres/functions.py index fc0dae8ece..d17f9cb37d 100644 --- a/django/contrib/postgres/functions.py +++ b/django/contrib/postgres/functions.py @@ -7,4 +7,4 @@ class TransactionNow(Func): def __init__(self, output_field=None, **extra): if output_field is None: output_field = DateTimeField() - super(TransactionNow, self).__init__(output_field=output_field, **extra) + super().__init__(output_field=output_field, **extra) diff --git a/django/contrib/postgres/indexes.py b/django/contrib/postgres/indexes.py index 2edec371f4..60578e6c16 100644 --- a/django/contrib/postgres/indexes.py +++ b/django/contrib/postgres/indexes.py @@ -10,7 +10,7 @@ class BrinIndex(Index): if pages_per_range is not None and pages_per_range <= 0: raise ValueError('pages_per_range must be None or a positive integer') self.pages_per_range = pages_per_range - super(BrinIndex, self).__init__(fields, name) + super().__init__(fields, name) def __repr__(self): if self.pages_per_range is not None: @@ -20,15 +20,15 @@ class BrinIndex(Index): 'pages_per_range': self.pages_per_range, } else: - return super(BrinIndex, self).__repr__() + return super().__repr__() def deconstruct(self): - path, args, kwargs = super(BrinIndex, self).deconstruct() + path, args, kwargs = super().deconstruct() kwargs['pages_per_range'] = self.pages_per_range return path, args, kwargs def get_sql_create_template_values(self, model, schema_editor, using): - parameters = super(BrinIndex, self).get_sql_create_template_values(model, schema_editor, using=' USING brin') + parameters = super().get_sql_create_template_values(model, schema_editor, using=' USING brin') if self.pages_per_range is not None: parameters['extra'] = ' WITH (pages_per_range={})'.format( schema_editor.quote_value(self.pages_per_range)) + parameters['extra'] @@ -39,4 +39,4 @@ class GinIndex(Index): suffix = 'gin' def create_sql(self, model, schema_editor): - return super(GinIndex, self).create_sql(model, schema_editor, using=' USING gin') + return super().create_sql(model, schema_editor, using=' USING gin') diff --git a/django/contrib/postgres/lookups.py b/django/contrib/postgres/lookups.py index 53a62eacd1..8521b26c6e 100644 --- a/django/contrib/postgres/lookups.py +++ b/django/contrib/postgres/lookups.py @@ -58,7 +58,7 @@ class SearchLookup(SearchVectorExact): def process_lhs(self, qn, connection): if not isinstance(self.lhs.output_field, SearchVectorField): self.lhs = SearchVector(self.lhs) - lhs, lhs_params = super(SearchLookup, self).process_lhs(qn, connection) + lhs, lhs_params = super().process_lhs(qn, connection) return lhs, lhs_params diff --git a/django/contrib/postgres/operations.py b/django/contrib/postgres/operations.py index cb45d4f705..7544e38613 100644 --- a/django/contrib/postgres/operations.py +++ b/django/contrib/postgres/operations.py @@ -41,7 +41,7 @@ class HStoreExtension(CreateExtension): self.name = 'hstore' def database_forwards(self, app_label, schema_editor, from_state, to_state): - super(HStoreExtension, self).database_forwards(app_label, schema_editor, from_state, to_state) + super().database_forwards(app_label, schema_editor, from_state, to_state) # Register hstore straight away as it cannot be done before the # extension is installed, a subsequent data migration would use the # same connection diff --git a/django/contrib/postgres/search.py b/django/contrib/postgres/search.py index bc9bb1052b..9a773db1d5 100644 --- a/django/contrib/postgres/search.py +++ b/django/contrib/postgres/search.py @@ -11,7 +11,7 @@ class SearchVectorExact(Lookup): if not hasattr(self.rhs, 'resolve_expression'): config = getattr(self.lhs, 'config', None) self.rhs = SearchQuery(self.rhs, config=config) - rhs, rhs_params = super(SearchVectorExact, self).process_rhs(qn, connection) + rhs, rhs_params = super().process_rhs(qn, connection) return rhs, rhs_params def as_sql(self, qn, connection): @@ -51,7 +51,7 @@ class SearchVector(SearchVectorCombinable, Func): config = None def __init__(self, *expressions, **extra): - super(SearchVector, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) self.source_expressions = [ Coalesce(expression, Value('')) for expression in self.source_expressions ] @@ -62,7 +62,7 @@ class SearchVector(SearchVectorCombinable, Func): self.weight = weight def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - resolved = super(SearchVector, self).resolve_expression(query, allow_joins, reuse, summarize, for_save) + resolved = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) if self.config: if not hasattr(self.config, 'resolve_expression'): resolved.config = Value(self.config).resolve_expression(query, allow_joins, reuse, summarize, for_save) @@ -78,7 +78,7 @@ class SearchVector(SearchVectorCombinable, Func): template = "%(function)s({}::regconfig, %(expressions)s)".format(config_sql.replace('%', '%%')) else: template = self.template - sql, params = super(SearchVector, self).as_sql(compiler, connection, function=function, template=template) + sql, params = super().as_sql(compiler, connection, function=function, template=template) extra_params = [] if self.weight: weight_sql, extra_params = compiler.compile(self.weight) @@ -89,7 +89,7 @@ class SearchVector(SearchVectorCombinable, Func): class CombinedSearchVector(SearchVectorCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config - super(CombinedSearchVector, self).__init__(lhs, connector, rhs, output_field) + super().__init__(lhs, connector, rhs, output_field) class SearchQueryCombinable: @@ -132,10 +132,10 @@ class SearchQuery(SearchQueryCombinable, Value): def __init__(self, value, output_field=None, **extra): self.config = extra.pop('config', self.config) self.invert = extra.pop('invert', self.invert) - super(SearchQuery, self).__init__(value, output_field=output_field) + super().__init__(value, output_field=output_field) def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - resolved = super(SearchQuery, self).resolve_expression(query, allow_joins, reuse, summarize, for_save) + resolved = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) if self.config: if not hasattr(self.config, 'resolve_expression'): resolved.config = Value(self.config).resolve_expression(query, allow_joins, reuse, summarize, for_save) @@ -156,7 +156,7 @@ class SearchQuery(SearchQueryCombinable, Value): return template, params def _combine(self, other, connector, reversed, node=None): - combined = super(SearchQuery, self)._combine(other, connector, reversed, node) + combined = super()._combine(other, connector, reversed, node) combined.output_field = SearchQueryField() return combined @@ -171,7 +171,7 @@ class SearchQuery(SearchQueryCombinable, Value): class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): def __init__(self, lhs, connector, rhs, config, output_field=None): self.config = config - super(CombinedSearchQuery, self).__init__(lhs, connector, rhs, output_field) + super().__init__(lhs, connector, rhs, output_field) class SearchRank(Func): @@ -187,7 +187,7 @@ class SearchRank(Func): if weights is not None and not hasattr(weights, 'resolve_expression'): weights = Value(weights) self.weights = weights - super(SearchRank, self).__init__(vector, query, **extra) + super().__init__(vector, query, **extra) def as_sql(self, compiler, connection, function=None, template=None): extra_params = [] @@ -197,7 +197,7 @@ class SearchRank(Func): template = '%(function)s(%(weights)s, %(expressions)s)' weight_sql, extra_params = compiler.compile(self.weights) extra_context['weights'] = weight_sql - sql, params = super(SearchRank, self).as_sql( + sql, params = super().as_sql( compiler, connection, function=function, template=template, **extra_context ) @@ -211,7 +211,7 @@ class TrigramBase(Func): def __init__(self, expression, string, **extra): if not hasattr(string, 'resolve_expression'): string = Value(string) - super(TrigramBase, self).__init__(expression, string, output_field=FloatField(), **extra) + super().__init__(expression, string, output_field=FloatField(), **extra) class TrigramSimilarity(TrigramBase): diff --git a/django/contrib/redirects/middleware.py b/django/contrib/redirects/middleware.py index 317dca3fd2..8bf4e26ec8 100644 --- a/django/contrib/redirects/middleware.py +++ b/django/contrib/redirects/middleware.py @@ -18,7 +18,7 @@ class RedirectFallbackMiddleware(MiddlewareMixin): "You cannot use RedirectFallbackMiddleware when " "django.contrib.sites is not installed." ) - super(RedirectFallbackMiddleware, self).__init__(get_response) + super().__init__(get_response) def process_response(self, request, response): # No need to check for a redirect for non-404 responses. diff --git a/django/contrib/sessions/backends/cache.py b/django/contrib/sessions/backends/cache.py index c64d7f6a6c..c0d17ca45a 100644 --- a/django/contrib/sessions/backends/cache.py +++ b/django/contrib/sessions/backends/cache.py @@ -15,7 +15,7 @@ class SessionStore(SessionBase): def __init__(self, session_key=None): self._cache = caches[settings.SESSION_CACHE_ALIAS] - super(SessionStore, self).__init__(session_key) + super().__init__(session_key) @property def cache_key(self): diff --git a/django/contrib/sessions/backends/cached_db.py b/django/contrib/sessions/backends/cached_db.py index 3f33e78c89..f830e072e7 100644 --- a/django/contrib/sessions/backends/cached_db.py +++ b/django/contrib/sessions/backends/cached_db.py @@ -22,7 +22,7 @@ class SessionStore(DBStore): def __init__(self, session_key=None): self._cache = caches[settings.SESSION_CACHE_ALIAS] - super(SessionStore, self).__init__(session_key) + super().__init__(session_key) @property def cache_key(self): @@ -57,14 +57,14 @@ class SessionStore(DBStore): def exists(self, session_key): if session_key and (self.cache_key_prefix + session_key) in self._cache: return True - return super(SessionStore, self).exists(session_key) + return super().exists(session_key) def save(self, must_create=False): - super(SessionStore, self).save(must_create) + super().save(must_create) self._cache.set(self.cache_key, self._session, self.get_expiry_age()) def delete(self, session_key=None): - super(SessionStore, self).delete(session_key) + super().delete(session_key) if session_key is None: if self.session_key is None: return diff --git a/django/contrib/sessions/backends/db.py b/django/contrib/sessions/backends/db.py index 95c2f0d225..a345e75157 100644 --- a/django/contrib/sessions/backends/db.py +++ b/django/contrib/sessions/backends/db.py @@ -15,7 +15,7 @@ class SessionStore(SessionBase): Implements database session store. """ def __init__(self, session_key=None): - super(SessionStore, self).__init__(session_key) + super().__init__(session_key) @classmethod def get_model_class(cls): diff --git a/django/contrib/sessions/backends/file.py b/django/contrib/sessions/backends/file.py index 83baa35ef2..fab83530ca 100644 --- a/django/contrib/sessions/backends/file.py +++ b/django/contrib/sessions/backends/file.py @@ -21,7 +21,7 @@ class SessionStore(SessionBase): def __init__(self, session_key=None): self.storage_path = type(self)._get_storage_path() self.file_prefix = settings.SESSION_COOKIE_NAME - super(SessionStore, self).__init__(session_key) + super().__init__(session_key) @classmethod def _get_storage_path(cls): diff --git a/django/contrib/sites/managers.py b/django/contrib/sites/managers.py index 52f91a51ea..91c034e967 100644 --- a/django/contrib/sites/managers.py +++ b/django/contrib/sites/managers.py @@ -10,11 +10,11 @@ class CurrentSiteManager(models.Manager): use_in_migrations = True def __init__(self, field_name=None): - super(CurrentSiteManager, self).__init__() + super().__init__() self.__field_name = field_name def check(self, **kwargs): - errors = super(CurrentSiteManager, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_field_name()) return errors @@ -57,5 +57,4 @@ class CurrentSiteManager(models.Manager): return self.__field_name def get_queryset(self): - return super(CurrentSiteManager, self).get_queryset().filter( - **{self._get_field_name() + '__id': settings.SITE_ID}) + return super().get_queryset().filter(**{self._get_field_name() + '__id': settings.SITE_ID}) diff --git a/django/contrib/staticfiles/finders.py b/django/contrib/staticfiles/finders.py index 08b25181bc..fcb31c8547 100644 --- a/django/contrib/staticfiles/finders.py +++ b/django/contrib/staticfiles/finders.py @@ -71,7 +71,7 @@ class FileSystemFinder(BaseFinder): filesystem_storage = FileSystemStorage(location=root) filesystem_storage.prefix = prefix self.storages[root] = filesystem_storage - super(FileSystemFinder, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def find(self, path, all=False): """ @@ -137,7 +137,7 @@ class AppDirectoriesFinder(BaseFinder): self.storages[app_config.name] = app_storage if app_config.name not in self.apps: self.apps.append(app_config.name) - super(AppDirectoriesFinder, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def list(self, ignore_patterns): """ @@ -194,7 +194,7 @@ class BaseStorageFinder(BaseFinder): # Make sure we have an storage instance here. if not isinstance(self.storage, (Storage, LazyObject)): self.storage = self.storage() - super(BaseStorageFinder, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def find(self, path, all=False): """ @@ -229,7 +229,7 @@ class DefaultStorageFinder(BaseStorageFinder): storage = default_storage def __init__(self, *args, **kwargs): - super(DefaultStorageFinder, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) base_location = getattr(self.storage, 'base_location', empty) if not base_location: raise ImproperlyConfigured("The storage backend of the " diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py index ce8b7e20c1..91b66d7a39 100644 --- a/django/contrib/staticfiles/handlers.py +++ b/django/contrib/staticfiles/handlers.py @@ -19,7 +19,7 @@ class StaticFilesHandler(WSGIHandler): def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) - super(StaticFilesHandler, self).__init__() + super().__init__() def get_base_url(self): utils.check_settings() @@ -57,9 +57,9 @@ class StaticFilesHandler(WSGIHandler): if settings.DEBUG: from django.views import debug return debug.technical_404_response(request, e) - return super(StaticFilesHandler, self).get_response(request) + return super().get_response(request) def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) - return super(StaticFilesHandler, self).__call__(environ, start_response) + return super().__call__(environ, start_response) diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py index 3ee6d354af..6fdb797e5e 100644 --- a/django/contrib/staticfiles/management/commands/collectstatic.py +++ b/django/contrib/staticfiles/management/commands/collectstatic.py @@ -20,7 +20,7 @@ class Command(BaseCommand): requires_system_checks = False def __init__(self, *args, **kwargs): - super(Command, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.copied_files = [] self.symlinked_files = [] self.unmodified_files = [] diff --git a/django/contrib/staticfiles/management/commands/findstatic.py b/django/contrib/staticfiles/management/commands/findstatic.py index 992dae1769..067b229f6d 100644 --- a/django/contrib/staticfiles/management/commands/findstatic.py +++ b/django/contrib/staticfiles/management/commands/findstatic.py @@ -10,7 +10,7 @@ class Command(LabelCommand): label = 'staticfile' def add_arguments(self, parser): - super(Command, self).add_arguments(parser) + super().add_arguments(parser) parser.add_argument( '--first', action='store_false', dest='all', default=True, diff --git a/django/contrib/staticfiles/management/commands/runserver.py b/django/contrib/staticfiles/management/commands/runserver.py index c25ac1f369..9146a12385 100644 --- a/django/contrib/staticfiles/management/commands/runserver.py +++ b/django/contrib/staticfiles/management/commands/runserver.py @@ -8,7 +8,7 @@ class Command(RunserverCommand): help = "Starts a lightweight Web server for development and also serves static files." def add_arguments(self, parser): - super(Command, self).add_arguments(parser) + super().add_arguments(parser) parser.add_argument( '--nostatic', action="store_false", dest='use_static_handler', default=True, help='Tells Django to NOT automatically serve static files at STATIC_URL.', @@ -24,7 +24,7 @@ class Command(RunserverCommand): if static files should be served. Otherwise just returns the default handler. """ - handler = super(Command, self).get_handler(*args, **options) + handler = super().get_handler(*args, **options) use_static_handler = options['use_static_handler'] insecure_serving = options['insecure_serving'] if use_static_handler and (settings.DEBUG or insecure_serving): diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py index 46b751b094..6648d2c705 100644 --- a/django/contrib/staticfiles/storage.py +++ b/django/contrib/staticfiles/storage.py @@ -31,8 +31,7 @@ class StaticFilesStorage(FileSystemStorage): if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) - super(StaticFilesStorage, self).__init__(location, base_url, - *args, **kwargs) + super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: @@ -44,7 +43,7 @@ class StaticFilesStorage(FileSystemStorage): raise ImproperlyConfigured("You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path.") - return super(StaticFilesStorage, self).path(name) + return super().path(name) class HashedFilesMixin: @@ -58,7 +57,7 @@ class HashedFilesMixin: ) def __init__(self, *args, **kwargs): - super(HashedFilesMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._patterns = OrderedDict() self.hashed_files = {} for extension, patterns in self.patterns: @@ -134,7 +133,7 @@ class HashedFilesMixin: args += (hashed_files,) hashed_name = hashed_name_func(*args) - final_url = super(HashedFilesMixin, self).url(hashed_name) + final_url = super().url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax @@ -376,7 +375,7 @@ class ManifestFilesMixin(HashedFilesMixin): manifest_strict = True def __init__(self, *args, **kwargs): - super(ManifestFilesMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.hashed_files = self.load_manifest() def read_manifest(self): @@ -403,8 +402,7 @@ class ManifestFilesMixin(HashedFilesMixin): def post_process(self, *args, **kwargs): self.hashed_files = OrderedDict() - all_post_processed = super(ManifestFilesMixin, - self).post_process(*args, **kwargs) + all_post_processed = super().post_process(*args, **kwargs) for post_processed in all_post_processed: yield post_processed self.save_manifest() @@ -465,7 +463,7 @@ class _MappingCache: class CachedFilesMixin(HashedFilesMixin): def __init__(self, *args, **kwargs): - super(CachedFilesMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) try: self.hashed_files = _MappingCache(caches['staticfiles']) except InvalidCacheBackendError: diff --git a/django/core/cache/backends/filebased.py b/django/core/cache/backends/filebased.py index 896f798e95..a381ebc265 100644 --- a/django/core/cache/backends/filebased.py +++ b/django/core/cache/backends/filebased.py @@ -17,7 +17,7 @@ class FileBasedCache(BaseCache): cache_suffix = '.djcache' def __init__(self, dir, params): - super(FileBasedCache, self).__init__(params) + super().__init__(params) self._dir = os.path.abspath(dir) self._createdir() diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py index 29bd2a95cd..6be2378e56 100644 --- a/django/core/cache/backends/memcached.py +++ b/django/core/cache/backends/memcached.py @@ -12,7 +12,7 @@ from django.utils.functional import cached_property class BaseMemcachedCache(BaseCache): def __init__(self, server, params, library, value_not_found_exception): - super(BaseMemcachedCache, self).__init__(params) + super().__init__(params) if isinstance(server, str): self._servers = re.split('[;,]', server) else: @@ -154,9 +154,7 @@ class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-memcached" def __init__(self, server, params): import memcache - super(MemcachedCache, self).__init__(server, params, - library=memcache, - value_not_found_exception=ValueError) + super().__init__(server, params, library=memcache, value_not_found_exception=ValueError) @property def _cache(self): @@ -171,9 +169,7 @@ class PyLibMCCache(BaseMemcachedCache): "An implementation of a cache binding using pylibmc" def __init__(self, server, params): import pylibmc - super(PyLibMCCache, self).__init__(server, params, - library=pylibmc, - value_not_found_exception=pylibmc.NotFound) + super().__init__(server, params, library=pylibmc, value_not_found_exception=pylibmc.NotFound) # The contents of `OPTIONS` was formerly only used to set the behaviors # attribute, but is now passed directly to the Client constructor. As such, diff --git a/django/core/checks/messages.py b/django/core/checks/messages.py index bb0e2b335c..62bd909c6f 100644 --- a/django/core/checks/messages.py +++ b/django/core/checks/messages.py @@ -54,24 +54,24 @@ class CheckMessage: class Debug(CheckMessage): def __init__(self, *args, **kwargs): - super(Debug, self).__init__(DEBUG, *args, **kwargs) + super().__init__(DEBUG, *args, **kwargs) class Info(CheckMessage): def __init__(self, *args, **kwargs): - super(Info, self).__init__(INFO, *args, **kwargs) + super().__init__(INFO, *args, **kwargs) class Warning(CheckMessage): def __init__(self, *args, **kwargs): - super(Warning, self).__init__(WARNING, *args, **kwargs) + super().__init__(WARNING, *args, **kwargs) class Error(CheckMessage): def __init__(self, *args, **kwargs): - super(Error, self).__init__(ERROR, *args, **kwargs) + super().__init__(ERROR, *args, **kwargs) class Critical(CheckMessage): def __init__(self, *args, **kwargs): - super(Critical, self).__init__(CRITICAL, *args, **kwargs) + super().__init__(CRITICAL, *args, **kwargs) diff --git a/django/core/exceptions.py b/django/core/exceptions.py index 3bf52fab00..983053ca5b 100644 --- a/django/core/exceptions.py +++ b/django/core/exceptions.py @@ -109,7 +109,7 @@ class ValidationError(Exception): """ # PY2 can't pickle naive exception: http://bugs.python.org/issue1692335. - super(ValidationError, self).__init__(message, code, params) + super().__init__(message, code, params) if isinstance(message, ValidationError): if hasattr(message, 'error_dict'): diff --git a/django/core/files/base.py b/django/core/files/base.py index 225c6dd349..9030ed9155 100644 --- a/django/core/files/base.py +++ b/django/core/files/base.py @@ -137,7 +137,7 @@ class ContentFile(File): """ def __init__(self, content, name=None): stream_class = StringIO if isinstance(content, str) else BytesIO - super(ContentFile, self).__init__(stream_class(content), name=name) + super().__init__(stream_class(content), name=name) self.size = len(content) def __str__(self): diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py index f5ab68f0fc..9f1efde419 100644 --- a/django/core/files/uploadedfile.py +++ b/django/core/files/uploadedfile.py @@ -24,7 +24,7 @@ class UploadedFile(File): DEFAULT_CHUNK_SIZE = 64 * 2 ** 10 def __init__(self, file=None, name=None, content_type=None, size=None, charset=None, content_type_extra=None): - super(UploadedFile, self).__init__(file, name) + super().__init__(file, name) self.size = size self.content_type = content_type self.charset = charset @@ -59,7 +59,7 @@ class TemporaryUploadedFile(UploadedFile): """ def __init__(self, name, content_type, size, charset, content_type_extra=None): file = tempfile.NamedTemporaryFile(suffix='.upload', dir=settings.FILE_UPLOAD_TEMP_DIR) - super(TemporaryUploadedFile, self).__init__(file, name, content_type, size, charset, content_type_extra) + super().__init__(file, name, content_type, size, charset, content_type_extra) def temporary_file_path(self): """ @@ -82,7 +82,7 @@ class InMemoryUploadedFile(UploadedFile): A file uploaded into memory (i.e. stream-to-memory). """ def __init__(self, file, field_name, name, content_type, size, charset, content_type_extra=None): - super(InMemoryUploadedFile, self).__init__(file, name, content_type, size, charset, content_type_extra) + super().__init__(file, name, content_type, size, charset, content_type_extra) self.field_name = field_name def open(self, mode=None): @@ -103,8 +103,7 @@ class SimpleUploadedFile(InMemoryUploadedFile): """ def __init__(self, name, content, content_type='text/plain'): content = content or b'' - super(SimpleUploadedFile, self).__init__(BytesIO(content), None, name, - content_type, len(content), None, None) + super().__init__(BytesIO(content), None, name, content_type, len(content), None, None) @classmethod def from_dict(cls, file_dict): diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index e8f87845c9..a6832491c1 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -133,13 +133,13 @@ class TemporaryFileUploadHandler(FileUploadHandler): Upload handler that streams data into a temporary file. """ def __init__(self, *args, **kwargs): - super(TemporaryFileUploadHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def new_file(self, *args, **kwargs): """ Create the file object to append to as data is coming in. """ - super(TemporaryFileUploadHandler, self).new_file(*args, **kwargs) + super().new_file(*args, **kwargs) self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, self.content_type_extra) def receive_data_chunk(self, raw_data, start): @@ -168,7 +168,7 @@ class MemoryFileUploadHandler(FileUploadHandler): self.activated = True def new_file(self, *args, **kwargs): - super(MemoryFileUploadHandler, self).new_file(*args, **kwargs) + super().new_file(*args, **kwargs) if self.activated: self.file = BytesIO() raise StopFutureHandlers() diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 7d8a12176a..2b3c355b9d 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -141,7 +141,7 @@ class WSGIHandler(base.BaseHandler): request_class = WSGIRequest def __init__(self, *args, **kwargs): - super(WSGIHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.load_middleware() def __call__(self, environ, start_response): diff --git a/django/core/mail/backends/console.py b/django/core/mail/backends/console.py index 49ddade984..a8bdcbd2c0 100644 --- a/django/core/mail/backends/console.py +++ b/django/core/mail/backends/console.py @@ -11,7 +11,7 @@ class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): self.stream = kwargs.pop('stream', sys.stdout) self._lock = threading.RLock() - super(EmailBackend, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def write_message(self, message): msg = message.message() diff --git a/django/core/mail/backends/filebased.py b/django/core/mail/backends/filebased.py index 40dc9ff7cc..b051fe6313 100644 --- a/django/core/mail/backends/filebased.py +++ b/django/core/mail/backends/filebased.py @@ -40,7 +40,7 @@ class EmailBackend(ConsoleEmailBackend): # Since we're using the console-based backend as a base, # force the stream to be None, so we don't default to stdout kwargs['stream'] = None - super(EmailBackend, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def write_message(self, message): self.stream.write(message.message().as_bytes() + b'\n') diff --git a/django/core/mail/backends/locmem.py b/django/core/mail/backends/locmem.py index 54d3847c03..f022236dd7 100644 --- a/django/core/mail/backends/locmem.py +++ b/django/core/mail/backends/locmem.py @@ -15,7 +15,7 @@ class EmailBackend(BaseEmailBackend): The dummy outbox is accessible through the outbox instance attribute. """ def __init__(self, *args, **kwargs): - super(EmailBackend, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if not hasattr(mail, 'outbox'): mail.outbox = [] diff --git a/django/core/mail/backends/smtp.py b/django/core/mail/backends/smtp.py index b6d5c2fed3..97b5df97e8 100644 --- a/django/core/mail/backends/smtp.py +++ b/django/core/mail/backends/smtp.py @@ -18,7 +18,7 @@ class EmailBackend(BaseEmailBackend): use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs): - super(EmailBackend, self).__init__(fail_silently=fail_silently) + super().__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT self.username = settings.EMAIL_HOST_USER if username is None else username diff --git a/django/core/mail/message.py b/django/core/mail/message.py index dd5e1e6d7b..f4f3eb1352 100644 --- a/django/core/mail/message.py +++ b/django/core/mail/message.py @@ -429,7 +429,7 @@ class EmailMultiAlternatives(EmailMessage): bytestrings). The SafeMIMEText class will handle any necessary encoding conversions. """ - super(EmailMultiAlternatives, self).__init__( + super().__init__( subject, body, from_email, to, bcc, connection, attachments, headers, cc, reply_to, ) diff --git a/django/core/management/base.py b/django/core/management/base.py index 80f7e0a575..b0f454381a 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -45,18 +45,18 @@ class CommandParser(ArgumentParser): """ def __init__(self, cmd, **kwargs): self.cmd = cmd - super(CommandParser, self).__init__(**kwargs) + super().__init__(**kwargs) def parse_args(self, args=None, namespace=None): # Catch missing argument for a better error message if (hasattr(self.cmd, 'missing_args_message') and not (args or any(not arg.startswith('-') for arg in args))): self.error(self.cmd.missing_args_message) - return super(CommandParser, self).parse_args(args, namespace) + return super().parse_args(args, namespace) def error(self, message): if self.cmd._called_from_command_line: - super(CommandParser, self).error(message) + super().error(message) else: raise CommandError("Error: %s" % message) diff --git a/django/core/management/commands/migrate.py b/django/core/management/commands/migrate.py index 79ff872db0..91c52f96ee 100644 --- a/django/core/management/commands/migrate.py +++ b/django/core/management/commands/migrate.py @@ -56,7 +56,7 @@ class Command(BaseCommand): def _run_checks(self, **kwargs): issues = run_checks(tags=[Tags.database]) - issues.extend(super(Command, self)._run_checks(**kwargs)) + issues.extend(super()._run_checks(**kwargs)) return issues def handle(self, *args, **options): diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py index 61a275d61f..2523c1b5f3 100644 --- a/django/core/management/commands/runserver.py +++ b/django/core/management/commands/runserver.py @@ -57,7 +57,7 @@ class Command(BaseCommand): # way to reach WSGIRequestHandler. This seems an acceptable # compromise considering `runserver` runs indefinitely. os.environ["DJANGO_COLORS"] = "nocolor" - super(Command, self).execute(*args, **options) + super().execute(*args, **options) def get_handler(self, *args, **options): """ diff --git a/django/core/management/commands/sqlflush.py b/django/core/management/commands/sqlflush.py index da7d6b00e9..60e69e67bf 100644 --- a/django/core/management/commands/sqlflush.py +++ b/django/core/management/commands/sqlflush.py @@ -12,7 +12,7 @@ class Command(BaseCommand): output_transaction = True def add_arguments(self, parser): - super(Command, self).add_arguments(parser) + super().add_arguments(parser) parser.add_argument( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the SQL for. Defaults to the "default" database.', diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py index f6c67a5807..0d04a54af3 100644 --- a/django/core/management/commands/sqlmigrate.py +++ b/django/core/management/commands/sqlmigrate.py @@ -27,7 +27,7 @@ class Command(BaseCommand): # no_color=True so that the BEGIN/COMMIT statements added by # output_transaction don't get colored either. options['no_color'] = True - return super(Command, self).execute(*args, **options) + return super().execute(*args, **options) def handle(self, *args, **options): # Get the database we're operating from diff --git a/django/core/management/commands/sqlsequencereset.py b/django/core/management/commands/sqlsequencereset.py index 788a923c72..d23f89ce1f 100644 --- a/django/core/management/commands/sqlsequencereset.py +++ b/django/core/management/commands/sqlsequencereset.py @@ -8,7 +8,7 @@ class Command(AppCommand): output_transaction = True def add_arguments(self, parser): - super(Command, self).add_arguments(parser) + super().add_arguments(parser) parser.add_argument( '--database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the SQL for. Defaults to the "default" database.', diff --git a/django/core/management/commands/startapp.py b/django/core/management/commands/startapp.py index 32e9454a3c..63ecba4372 100644 --- a/django/core/management/commands/startapp.py +++ b/django/core/management/commands/startapp.py @@ -26,4 +26,4 @@ class Command(TemplateCommand): "cannot be used as an app name. Please try another name." % app_name ) - super(Command, self).handle('app', app_name, target, **options) + super().handle('app', app_name, target, **options) diff --git a/django/core/management/commands/startproject.py b/django/core/management/commands/startproject.py index d7307e141b..bc64faa680 100644 --- a/django/core/management/commands/startproject.py +++ b/django/core/management/commands/startproject.py @@ -31,4 +31,4 @@ class Command(TemplateCommand): # Create a random SECRET_KEY to put it in the main settings. options['secret_key'] = get_random_secret_key() - super(Command, self).handle('project', project_name, target, **options) + super().handle('project', project_name, target, **options) diff --git a/django/core/management/commands/test.py b/django/core/management/commands/test.py index b1186f20fc..da2e4f5952 100644 --- a/django/core/management/commands/test.py +++ b/django/core/management/commands/test.py @@ -13,7 +13,7 @@ class Command(BaseCommand): def __init__(self): self.test_runner = None - super(Command, self).__init__() + super().__init__() def run_from_argv(self, argv): """ @@ -26,7 +26,7 @@ class Command(BaseCommand): if arg.startswith(option): self.test_runner = arg[len(option):] break - super(Command, self).run_from_argv(argv) + super().run_from_argv(argv) def add_arguments(self, parser): parser.add_argument( diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index 79db71cadf..b2ab87b171 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -59,7 +59,7 @@ class Serializer(PythonSerializer): self._current = None def getvalue(self): - # Grand-parent super + # Grandparent super return super(PythonSerializer, self).getvalue() @@ -108,4 +108,4 @@ class DjangoJSONEncoder(json.JSONEncoder): elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): return str(o) else: - return super(DjangoJSONEncoder, self).default(o) + return super().default(o) diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py index 89594728cb..fcebd107aa 100644 --- a/django/core/serializers/pyyaml.py +++ b/django/core/serializers/pyyaml.py @@ -53,13 +53,13 @@ class Serializer(PythonSerializer): if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None: self._current[field.name] = str(getattr(obj, field.name)) else: - super(Serializer, self).handle_field(obj, field) + super().handle_field(obj, field) def end_serialization(self): yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options) def getvalue(self): - # Grand-parent super + # Grandparent super return super(PythonSerializer, self).getvalue() diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index e209cb286a..ddf0bf3e1a 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -158,7 +158,7 @@ class Deserializer(base.Deserializer): """ def __init__(self, stream_or_string, **options): - super(Deserializer, self).__init__(stream_or_string, **options) + super().__init__(stream_or_string, **options) self.event_stream = pulldom.parse(self.stream, self._make_parser()) self.db = options.pop('using', DEFAULT_DB_ALIAS) self.ignore = options.pop('ignorenonexistent', False) @@ -356,7 +356,7 @@ class DefusedXmlException(ValueError): class DTDForbidden(DefusedXmlException): """Document type definition is forbidden.""" def __init__(self, name, sysid, pubid): - super(DTDForbidden, self).__init__() + super().__init__() self.name = name self.sysid = sysid self.pubid = pubid @@ -369,7 +369,7 @@ class DTDForbidden(DefusedXmlException): class EntitiesForbidden(DefusedXmlException): """Entity definition is forbidden.""" def __init__(self, name, value, base, sysid, pubid, notation_name): - super(EntitiesForbidden, self).__init__() + super().__init__() self.name = name self.value = value self.base = base @@ -385,7 +385,7 @@ class EntitiesForbidden(DefusedXmlException): class ExternalReferenceForbidden(DefusedXmlException): """Resolving an external reference is forbidden.""" def __init__(self, context, base, sysid, pubid): - super(ExternalReferenceForbidden, self).__init__() + super().__init__() self.context = context self.base = base self.sysid = sysid diff --git a/django/core/servers/basehttp.py b/django/core/servers/basehttp.py index 3e1141122b..ef2edc0f80 100644 --- a/django/core/servers/basehttp.py +++ b/django/core/servers/basehttp.py @@ -63,25 +63,25 @@ class WSGIServer(simple_server.WSGIServer): if kwargs.pop('ipv6', False): self.address_family = socket.AF_INET6 self.allow_reuse_address = kwargs.pop('allow_reuse_address', True) - super(WSGIServer, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def server_bind(self): """Override server_bind to store the server name.""" - super(WSGIServer, self).server_bind() + super().server_bind() self.setup_environ() def handle_error(self, request, client_address): if is_broken_pipe_error(): logger.info("- Broken pipe from %s\n", client_address) else: - super(WSGIServer, self).handle_error(request, client_address) + super().handle_error(request, client_address) class ServerHandler(simple_server.ServerHandler): def handle_error(self): # Ignore broken pipe errors, otherwise pass on if not is_broken_pipe_error(): - super(ServerHandler, self).handle_error() + super().handle_error() class WSGIRequestHandler(simple_server.WSGIRequestHandler): @@ -128,7 +128,7 @@ class WSGIRequestHandler(simple_server.WSGIRequestHandler): if '_' in k: del self.headers[k] - return super(WSGIRequestHandler, self).get_environ() + return super().get_environ() def handle(self): """Copy of WSGIRequestHandler, but with different ServerHandler""" diff --git a/django/core/signing.py b/django/core/signing.py index 7d73611817..b6a9a974c4 100644 --- a/django/core/signing.py +++ b/django/core/signing.py @@ -182,14 +182,14 @@ class TimestampSigner(Signer): def sign(self, value): value = '%s%s%s' % (force_text(value), self.sep, self.timestamp()) - return super(TimestampSigner, self).sign(value) + return super().sign(value) def unsign(self, value, max_age=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. """ - result = super(TimestampSigner, self).unsign(value) + result = super().unsign(value) value, timestamp = result.rsplit(self.sep, 1) timestamp = baseconv.base62.decode(timestamp) if max_age is not None: diff --git a/django/core/validators.py b/django/core/validators.py index 1dc0f2fbcd..0b90b4345c 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -102,7 +102,7 @@ class URLValidator(RegexValidator): schemes = ['http', 'https', 'ftp', 'ftps'] def __init__(self, schemes=None, **kwargs): - super(URLValidator, self).__init__(**kwargs) + super().__init__(**kwargs) if schemes is not None: self.schemes = schemes @@ -115,7 +115,7 @@ class URLValidator(RegexValidator): # Then check full URL try: - super(URLValidator, self).__call__(value) + super().__call__(value) except ValidationError as e: # Trivial case failed. Try for possible IDN domain if value: @@ -128,7 +128,7 @@ class URLValidator(RegexValidator): except UnicodeError: # invalid domain part raise e url = urlunsplit((scheme, netloc, path, query, fragment)) - super(URLValidator, self).__call__(url) + super().__call__(url) else: raise else: diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py index 457c8b7f48..20e017120c 100644 --- a/django/db/backends/mysql/introspection.py +++ b/django/db/backends/mysql/introspection.py @@ -39,7 +39,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): } def get_field_type(self, data_type, description): - field_type = super(DatabaseIntrospection, self).get_field_type(data_type, description) + field_type = super().get_field_type(data_type, description) if 'auto_increment' in description.extra: if field_type == 'IntegerField': return 'AutoField' diff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py index acb86c62ac..881ada60c7 100644 --- a/django/db/backends/mysql/operations.py +++ b/django/db/backends/mysql/operations.py @@ -202,10 +202,10 @@ class DatabaseOperations(BaseDatabaseOperations): elif connector == '>>': lhs, rhs = sub_expressions return 'FLOOR(%(lhs)s / POW(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} - return super(DatabaseOperations, self).combine_expression(connector, sub_expressions) + return super().combine_expression(connector, sub_expressions) def get_db_converters(self, expression): - converters = super(DatabaseOperations, self).get_db_converters(expression) + converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == 'TextField': converters.append(self.convert_textfield_value) diff --git a/django/db/backends/mysql/schema.py b/django/db/backends/mysql/schema.py index f89088ef5b..455fd1b0e3 100644 --- a/django/db/backends/mysql/schema.py +++ b/django/db/backends/mysql/schema.py @@ -45,7 +45,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): ) def add_field(self, model, field): - super(DatabaseSchemaEditor, self).add_field(model, field) + super().add_field(model, field) # Simulate the effect of a one-off default. # field.default may be unhashable, so a set isn't used for "in" check. @@ -57,7 +57,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): }, [effective_default]) def _field_should_be_indexed(self, model, field): - create_index = super(DatabaseSchemaEditor, self)._field_should_be_indexed(model, field) + create_index = super()._field_should_be_indexed(model, field) storage = self.connection.introspection.get_storage_engine( self.connection.cursor(), model._meta.db_table ) @@ -85,7 +85,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): constraint_names = self._constraint_names(model, [first_field.column], index=True) if not constraint_names: self.execute(self._create_index_sql(model, [first_field], suffix="")) - return super(DatabaseSchemaEditor, self)._delete_composed_index(model, fields, *args) + return super()._delete_composed_index(model, fields, *args) def _set_field_new_type_null_status(self, field, new_type): """ @@ -100,8 +100,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def _alter_column_type_sql(self, table, old_field, new_field, new_type): new_type = self._set_field_new_type_null_status(old_field, new_type) - return super(DatabaseSchemaEditor, self)._alter_column_type_sql(table, old_field, new_field, new_type) + return super()._alter_column_type_sql(table, old_field, new_field, new_type) def _rename_field_sql(self, table, old_field, new_field, new_type): new_type = self._set_field_new_type_null_status(old_field, new_type) - return super(DatabaseSchemaEditor, self)._rename_field_sql(table, old_field, new_field, new_type) + return super()._rename_field_sql(table, old_field, new_field, new_type) diff --git a/django/db/backends/mysql/validation.py b/django/db/backends/mysql/validation.py index 3492034eba..358520d517 100644 --- a/django/db/backends/mysql/validation.py +++ b/django/db/backends/mysql/validation.py @@ -5,7 +5,7 @@ from django.utils.version import get_docs_version class DatabaseValidation(BaseDatabaseValidation): def check(self, **kwargs): - issues = super(DatabaseValidation, self).check(**kwargs) + issues = super().check(**kwargs) issues.extend(self._check_sql_mode(**kwargs)) return issues @@ -32,7 +32,7 @@ class DatabaseValidation(BaseDatabaseValidation): No character (varchar) fields can have a length exceeding 255 characters if they have a unique index on them. """ - errors = super(DatabaseValidation, self).check_field(field, **kwargs) + errors = super().check_field(field, **kwargs) # Ignore any related fields. if getattr(field, 'remote_field', None): diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index fbbee227ee..0cc21b639b 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -175,7 +175,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): ops_class = DatabaseOperations def __init__(self, *args, **kwargs): - super(DatabaseWrapper, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) use_returning_into = self.settings_dict["OPTIONS"].get('use_returning_into', True) self.features.can_return_id_from_insert = use_returning_into diff --git a/django/db/backends/oracle/compiler.py b/django/db/backends/oracle/compiler.py index 9aa4acc0fe..4eb841f41f 100644 --- a/django/db/backends/oracle/compiler.py +++ b/django/db/backends/oracle/compiler.py @@ -16,15 +16,9 @@ class SQLCompiler(compiler.SQLCompiler): # the SQL needed to use limit/offset with Oracle. do_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark) if not do_offset: - sql, params = super(SQLCompiler, self).as_sql( - with_limits=False, - with_col_aliases=with_col_aliases, - ) + sql, params = super().as_sql(with_limits=False, with_col_aliases=with_col_aliases) else: - sql, params = super(SQLCompiler, self).as_sql( - with_limits=False, - with_col_aliases=True, - ) + sql, params = super().as_sql(with_limits=False, with_col_aliases=True) # Wrap the base query in an outer SELECT * with boundaries on # the "_RN" column. This is the canonical way to emulate LIMIT # and OFFSET on Oracle. diff --git a/django/db/backends/oracle/features.py b/django/db/backends/oracle/features.py index d30c149ad2..0e85f267f2 100644 --- a/django/db/backends/oracle/features.py +++ b/django/db/backends/oracle/features.py @@ -49,4 +49,4 @@ class DatabaseFeatures(BaseDatabaseFeatures): """ if self.connection.oracle_full_version < '11.2.0.2' and field and field.has_default() and created_separately: return 'IntegerField' - return super(DatabaseFeatures, self).introspected_boolean_field_type(field, created_separately) + return super().introspected_boolean_field_type(field, created_separately) diff --git a/django/db/backends/oracle/functions.py b/django/db/backends/oracle/functions.py index 384f092fd4..7e9b6a6204 100644 --- a/django/db/backends/oracle/functions.py +++ b/django/db/backends/oracle/functions.py @@ -12,7 +12,7 @@ class IntervalToSeconds(Func): def __init__(self, expression, **extra): output_field = extra.pop('output_field', DecimalField()) - super(IntervalToSeconds, self).__init__(expression, output_field=output_field, **extra) + super().__init__(expression, output_field=output_field, **extra) class SecondsToInterval(Func): @@ -21,4 +21,4 @@ class SecondsToInterval(Func): def __init__(self, expression, **extra): output_field = extra.pop('output_field', DurationField()) - super(SecondsToInterval, self).__init__(expression, output_field=output_field, **extra) + super().__init__(expression, output_field=output_field, **extra) diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py index 8a648dba3f..1250a02f1d 100644 --- a/django/db/backends/oracle/introspection.py +++ b/django/db/backends/oracle/introspection.py @@ -48,7 +48,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): elif scale == -127: return 'FloatField' - return super(DatabaseIntrospection, self).get_field_type(data_type, description) + return super().get_field_type(data_type, description) def get_table_list(self, cursor): """ diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py index 8d94319987..5a182d59e9 100644 --- a/django/db/backends/oracle/operations.py +++ b/django/db/backends/oracle/operations.py @@ -40,7 +40,7 @@ END; /""" def __init__(self, *args, **kwargs): - super(DatabaseOperations, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.set_operators['difference'] = 'MINUS' def autoinc_sql(self, table, column): @@ -165,7 +165,7 @@ WHEN (new.%(col_name)s IS NULL) return sql def get_db_converters(self, expression): - converters = super(DatabaseOperations, self).get_db_converters(expression) + converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == 'TextField': converters.append(self.convert_textfield_value) @@ -254,7 +254,7 @@ WHEN (new.%(col_name)s IS NULL) statement = cursor.statement # Unlike Psycopg's `query` and MySQLdb`'s `_last_executed`, CxOracle's # `statement` doesn't contain the query parameters. refs #20010. - return super(DatabaseOperations, self).last_executed_query(cursor, statement, params) + return super().last_executed_query(cursor, statement, params) def last_insert_id(self, cursor, table_name, pk_name): sq_name = self._get_sequence_name(table_name) @@ -514,7 +514,7 @@ WHEN (new.%(col_name)s IS NULL) return 'FLOOR(%(lhs)s / POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} elif connector == '^': return 'POWER(%s)' % ','.join(sub_expressions) - return super(DatabaseOperations, self).combine_expression(connector, sub_expressions) + return super().combine_expression(connector, sub_expressions) def _get_sequence_name(self, table): name_length = self.max_name_length() - 3 @@ -537,4 +537,4 @@ WHEN (new.%(col_name)s IS NULL) lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs return "NUMTODSINTERVAL(%s - %s, 'DAY')" % (lhs_sql, rhs_sql), lhs_params + rhs_params - return super(DatabaseOperations, self).subtract_temporals(internal_type, lhs, rhs) + return super().subtract_temporals(internal_type, lhs, rhs) diff --git a/django/db/backends/oracle/schema.py b/django/db/backends/oracle/schema.py index 44a1f3cd8d..1ce27dc29d 100644 --- a/django/db/backends/oracle/schema.py +++ b/django/db/backends/oracle/schema.py @@ -33,7 +33,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def delete_model(self, model): # Run superclass action - super(DatabaseSchemaEditor, self).delete_model(model) + super().delete_model(model) # Clean up any autoincrement trigger self.execute(""" DECLARE @@ -49,7 +49,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def alter_field(self, model, old_field, new_field, strict=False): try: - super(DatabaseSchemaEditor, self).alter_field(model, old_field, new_field, strict) + super().alter_field(model, old_field, new_field, strict) except DatabaseError as e: description = str(e) # If we're changing type to an unsupported type we need a @@ -100,7 +100,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): # Drop the old field self.remove_field(model, old_field) # Rename and possibly make the new field NOT NULL - super(DatabaseSchemaEditor, self).alter_field(model, new_temp_field, new_field) + super().alter_field(model, new_temp_field, new_field) def normalize_name(self, name): """ diff --git a/django/db/backends/postgresql/base.py b/django/db/backends/postgresql/base.py index a3b293ee36..2459748f1b 100644 --- a/django/db/backends/postgresql/base.py +++ b/django/db/backends/postgresql/base.py @@ -141,7 +141,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): ops_class = DatabaseOperations def __init__(self, *args, **kwargs): - super(DatabaseWrapper, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._named_cursor_idx = 0 def get_connection_params(self): @@ -248,7 +248,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): @property def _nodb_connection(self): - nodb_connection = super(DatabaseWrapper, self)._nodb_connection + nodb_connection = super()._nodb_connection try: nodb_connection.ensure_connection() except (Database.DatabaseError, WrappedDatabaseError): diff --git a/django/db/backends/postgresql/introspection.py b/django/db/backends/postgresql/introspection.py index 34150c6f48..d663de61e5 100644 --- a/django/db/backends/postgresql/introspection.py +++ b/django/db/backends/postgresql/introspection.py @@ -43,7 +43,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): AND c.relname = %s""" def get_field_type(self, data_type, description): - field_type = super(DatabaseIntrospection, self).get_field_type(data_type, description) + field_type = super().get_field_type(data_type, description) if description.default and 'nextval' in description.default: if field_type == 'IntegerField': return 'AutoField' diff --git a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py index 542fe223cb..e612a60ca8 100644 --- a/django/db/backends/postgresql/operations.py +++ b/django/db/backends/postgresql/operations.py @@ -261,7 +261,7 @@ class DatabaseOperations(BaseDatabaseOperations): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs return "age(%s, %s)" % (lhs_sql, rhs_sql), lhs_params + rhs_params - return super(DatabaseOperations, self).subtract_temporals(internal_type, lhs, rhs) + return super().subtract_temporals(internal_type, lhs, rhs) def fulltext_search_sql(self, field_name): raise NotImplementedError( diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py index bffa8bd45b..e9928999db 100644 --- a/django/db/backends/postgresql/schema.py +++ b/django/db/backends/postgresql/schema.py @@ -23,7 +23,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): return psycopg2.extensions.adapt(value) def _field_indexes_sql(self, model, field): - output = super(DatabaseSchemaEditor, self)._field_indexes_sql(model, field) + output = super()._field_indexes_sql(model, field) like_index_statement = self._create_like_index_sql(model, field) if like_index_statement is not None: output.append(like_index_statement) @@ -101,13 +101,11 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): ], ) else: - return super(DatabaseSchemaEditor, self)._alter_column_type_sql( - table, old_field, new_field, new_type - ) + return super()._alter_column_type_sql(table, old_field, new_field, new_type) def _alter_field(self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False): - super(DatabaseSchemaEditor, self)._alter_field( + super()._alter_field( model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict, ) diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py index 64486be737..4f66b66de9 100644 --- a/django/db/backends/sqlite3/operations.py +++ b/django/db/backends/sqlite3/operations.py @@ -195,7 +195,7 @@ class DatabaseOperations(BaseDatabaseOperations): return str(value) def get_db_converters(self, expression): - converters = super(DatabaseOperations, self).get_db_converters(expression) + converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == 'DateTimeField': converters.append(self.convert_datetimefield_value) @@ -256,7 +256,7 @@ class DatabaseOperations(BaseDatabaseOperations): # user-defined function django_power that's registered in connect(). if connector == '^': return 'django_power(%s)' % ','.join(sub_expressions) - return super(DatabaseOperations, self).combine_expression(connector, sub_expressions) + return super().combine_expression(connector, sub_expressions) def combine_duration_expression(self, connector, sub_expressions): if connector not in ['+', '-']: diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index d74f59d21c..bf2824aa1f 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -23,10 +23,10 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): c.execute('PRAGMA foreign_keys') self._initial_pragma_fk = c.fetchone()[0] c.execute('PRAGMA foreign_keys = 0') - return super(DatabaseSchemaEditor, self).__enter__() + return super().__enter__() def __exit__(self, exc_type, exc_value, traceback): - super(DatabaseSchemaEditor, self).__exit__(exc_type, exc_value, traceback) + super().__exit__(exc_type, exc_value, traceback) with self.connection.cursor() as c: # Restore initial FK setting - PRAGMA values can't be parametrized c.execute('PRAGMA foreign_keys = %s' % int(self._initial_pragma_fk)) @@ -216,7 +216,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def delete_model(self, model, handle_autom2m=True): if handle_autom2m: - super(DatabaseSchemaEditor, self).delete_model(model) + super().delete_model(model) else: # Delete the table (and only that) self.execute(self.sql_delete_table % { diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py index 3baff0d3d5..5da4e04478 100644 --- a/django/db/backends/utils.py +++ b/django/db/backends/utils.py @@ -74,7 +74,7 @@ class CursorDebugWrapper(CursorWrapper): def execute(self, sql, params=None): start = time() try: - return super(CursorDebugWrapper, self).execute(sql, params) + return super().execute(sql, params) finally: stop = time() duration = stop - start @@ -91,7 +91,7 @@ class CursorDebugWrapper(CursorWrapper): def executemany(self, sql, param_list): start = time() try: - return super(CursorDebugWrapper, self).executemany(sql, param_list) + return super().executemany(sql, param_list) finally: stop = time() duration = stop - start diff --git a/django/db/migrations/graph.py b/django/db/migrations/graph.py index 7fdc850a77..e8c67184a5 100644 --- a/django/db/migrations/graph.py +++ b/django/db/migrations/graph.py @@ -77,7 +77,7 @@ class Node: class DummyNode(Node): def __init__(self, key, origin, error_message): - super(DummyNode, self).__init__(key) + super().__init__(key) self.origin = origin self.error_message = error_message diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py index 431f87d7e6..20c1265d70 100644 --- a/django/db/migrations/operations/fields.py +++ b/django/db/migrations/operations/fields.py @@ -31,7 +31,7 @@ class FieldOperation(Operation): def reduce(self, operation, in_between, app_label=None): return ( - super(FieldOperation, self).reduce(operation, in_between, app_label=app_label) or + super().reduce(operation, in_between, app_label=app_label) or not operation.references_field(self.model_name, self.name, app_label) ) @@ -44,7 +44,7 @@ class AddField(FieldOperation): def __init__(self, model_name, name, field, preserve_default=True): self.field = field self.preserve_default = preserve_default - super(AddField, self).__init__(model_name, name) + super().__init__(model_name, name) def deconstruct(self): kwargs = { @@ -114,7 +114,7 @@ class AddField(FieldOperation): field=self.field, ), ] - return super(AddField, self).reduce(operation, in_between, app_label=app_label) + return super().reduce(operation, in_between, app_label=app_label) class RemoveField(FieldOperation): @@ -169,7 +169,7 @@ class AlterField(FieldOperation): def __init__(self, model_name, name, field, preserve_default=True): self.field = field self.preserve_default = preserve_default - super(AlterField, self).__init__(model_name, name) + super().__init__(model_name, name) def deconstruct(self): kwargs = { @@ -232,7 +232,7 @@ class AlterField(FieldOperation): field=self.field, ), ] - return super(AlterField, self).reduce(operation, in_between, app_label=app_label) + return super().reduce(operation, in_between, app_label=app_label) class RenameField(FieldOperation): @@ -243,7 +243,7 @@ class RenameField(FieldOperation): def __init__(self, model_name, old_name, new_name): self.old_name = old_name self.new_name = new_name - super(RenameField, self).__init__(model_name, old_name) + super().__init__(model_name, old_name) @cached_property def old_name_lower(self): diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index f376324580..34a0c4e2ef 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -33,7 +33,7 @@ class ModelOperation(Operation): def reduce(self, operation, in_between, app_label=None): return ( - super(ModelOperation, self).reduce(operation, in_between, app_label=app_label) or + super().reduce(operation, in_between, app_label=app_label) or not operation.references_model(self.name, app_label) ) @@ -50,7 +50,7 @@ class CreateModel(ModelOperation): self.options = options or {} self.bases = bases or (models.Model,) self.managers = managers or [] - super(CreateModel, self).__init__(name) + super().__init__(name) # Sanity-check that there are no duplicated field names, bases, or # manager names _check_for_duplicates('fields', (name for name, _ in self.fields)) @@ -223,7 +223,7 @@ class CreateModel(ModelOperation): managers=self.managers, ), ] - return super(CreateModel, self).reduce(operation, in_between, app_label=app_label) + return super().reduce(operation, in_between, app_label=app_label) class DeleteModel(ModelOperation): @@ -266,7 +266,7 @@ class RenameModel(ModelOperation): def __init__(self, old_name, new_name): self.old_name = old_name self.new_name = new_name - super(RenameModel, self).__init__(old_name) + super().__init__(old_name) @cached_property def old_name_lower(self): @@ -429,7 +429,7 @@ class AlterModelTable(ModelOperation): def __init__(self, name, table): self.table = table - super(AlterModelTable, self).__init__(name) + super().__init__(name) def deconstruct(self): kwargs = { @@ -476,14 +476,14 @@ class AlterModelTable(ModelOperation): def reduce(self, operation, in_between, app_label=None): if isinstance(operation, (AlterModelTable, DeleteModel)) and self.name_lower == operation.name_lower: return [operation] - return super(AlterModelTable, self).reduce(operation, in_between, app_label=app_label) + return super().reduce(operation, in_between, app_label=app_label) class ModelOptionOperation(ModelOperation): def reduce(self, operation, in_between, app_label=None): if isinstance(operation, (self.__class__, DeleteModel)) and self.name_lower == operation.name_lower: return [operation] - return super(ModelOptionOperation, self).reduce(operation, in_between, app_label=app_label) + return super().reduce(operation, in_between, app_label=app_label) class FieldRelatedOptionOperation(ModelOptionOperation): @@ -492,7 +492,7 @@ class FieldRelatedOptionOperation(ModelOptionOperation): self.name_lower == operation.model_name_lower and not self.references_field(operation.model_name, operation.name)): return [operation, self] - return super(FieldRelatedOptionOperation, self).reduce(operation, in_between, app_label=app_label) + return super().reduce(operation, in_between, app_label=app_label) class AlterUniqueTogether(FieldRelatedOptionOperation): @@ -505,7 +505,7 @@ class AlterUniqueTogether(FieldRelatedOptionOperation): def __init__(self, name, unique_together): unique_together = normalize_together(unique_together) self.unique_together = set(tuple(cons) for cons in unique_together) - super(AlterUniqueTogether, self).__init__(name) + super().__init__(name) def deconstruct(self): kwargs = { @@ -559,7 +559,7 @@ class AlterIndexTogether(FieldRelatedOptionOperation): def __init__(self, name, index_together): index_together = normalize_together(index_together) self.index_together = set(tuple(cons) for cons in index_together) - super(AlterIndexTogether, self).__init__(name) + super().__init__(name) def deconstruct(self): kwargs = { @@ -610,7 +610,7 @@ class AlterOrderWithRespectTo(FieldRelatedOptionOperation): def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to - super(AlterOrderWithRespectTo, self).__init__(name) + super().__init__(name) def deconstruct(self): kwargs = { @@ -685,7 +685,7 @@ class AlterModelOptions(ModelOptionOperation): def __init__(self, name, options): self.options = options - super(AlterModelOptions, self).__init__(name) + super().__init__(name) def deconstruct(self): kwargs = { @@ -726,7 +726,7 @@ class AlterModelManagers(ModelOptionOperation): def __init__(self, name, managers): self.managers = managers - super(AlterModelManagers, self).__init__(name) + super().__init__(name) def deconstruct(self): return ( diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index 58f90beaa2..fac8e4c189 100644 --- a/django/db/migrations/serializer.py +++ b/django/db/migrations/serializer.py @@ -136,7 +136,7 @@ class FloatSerializer(BaseSimpleSerializer): def serialize(self): if math.isnan(self.value) or math.isinf(self.value): return 'float("{}")'.format(self.value), set() - return super(FloatSerializer, self).serialize() + return super().serialize() class FrozensetSerializer(BaseSequenceSerializer): diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index 9e73fb20fd..de0b17422a 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -246,7 +246,7 @@ class AppConfigStub(AppConfig): # App-label and app-name are not the same thing, so technically passing # in the label here is wrong. In practice, migrations don't care about # the app name, but we need something unique, and the label works fine. - super(AppConfigStub, self).__init__(label, None) + super().__init__(label, None) def import_models(self): self.models = self.apps.all_models[self.label] @@ -271,7 +271,7 @@ class StateApps(Apps): # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] - super(StateApps, self).__init__(app_configs) + super().__init__(app_configs) # The lock gets in the way of copying as implemented in clone(), which # is called whenever Django duplicates a StateApps before updating it. diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index 6c320ed828..095455f8c1 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -16,7 +16,7 @@ class Aggregate(Func): def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): # Aggregates are not allowed in UPDATE queries, so ignore for_save - c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize) + c = super().resolve_expression(query, allow_joins, reuse, summarize) if not summarize: expressions = c.get_source_expressions() for index, expr in enumerate(expressions): @@ -45,7 +45,7 @@ class Avg(Aggregate): source_field = self.get_source_fields()[0] if isinstance(source_field, (IntegerField, DecimalField)): self._output_field = FloatField() - super(Avg, self)._resolve_output_field() + super()._resolve_output_field() def as_oracle(self, compiler, connection): if self.output_field.get_internal_type() == 'DurationField': @@ -54,7 +54,7 @@ class Avg(Aggregate): return compiler.compile( SecondsToInterval(Avg(IntervalToSeconds(expression))) ) - return super(Avg, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class Count(Aggregate): @@ -65,8 +65,10 @@ class Count(Aggregate): def __init__(self, expression, distinct=False, **extra): if expression == '*': expression = Star() - super(Count, self).__init__( - expression, distinct='DISTINCT ' if distinct else '', output_field=IntegerField(), **extra) + super().__init__( + expression, distinct='DISTINCT ' if distinct else '', + output_field=IntegerField(), **extra + ) def __repr__(self): return "{}({}, distinct={})".format( @@ -96,7 +98,7 @@ class StdDev(Aggregate): def __init__(self, expression, sample=False, **extra): self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP' - super(StdDev, self).__init__(expression, output_field=FloatField(), **extra) + super().__init__(expression, output_field=FloatField(), **extra) def __repr__(self): return "{}({}, sample={})".format( @@ -122,7 +124,7 @@ class Sum(Aggregate): return compiler.compile( SecondsToInterval(Sum(IntervalToSeconds(expression))) ) - return super(Sum, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class Variance(Aggregate): @@ -130,7 +132,7 @@ class Variance(Aggregate): def __init__(self, expression, sample=False, **extra): self.function = 'VAR_SAMP' if sample else 'VAR_POP' - super(Variance, self).__init__(expression, output_field=FloatField(), **extra) + super().__init__(expression, output_field=FloatField(), **extra) def __repr__(self): return "{}({}, sample={})".format( diff --git a/django/db/models/base.py b/django/db/models/base.py index 66b671698d..497a18f51a 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -73,7 +73,7 @@ class ModelBase(type): Metaclass for all models. """ def __new__(cls, name, bases, attrs): - super_new = super(ModelBase, cls).__new__ + super_new = super().__new__ # Also ensure initialization is only performed for subclasses of Model # (excluding Model class itself). @@ -486,7 +486,7 @@ class Model(metaclass=ModelBase): pass if kwargs: raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) - super(Model, self).__init__() + super().__init__() post_init.send(sender=cls, instance=self) @classmethod diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py index b0c61d1799..9da5caaedb 100644 --- a/django/db/models/deletion.py +++ b/django/db/models/deletion.py @@ -8,7 +8,7 @@ from django.db.models import signals, sql class ProtectedError(IntegrityError): def __init__(self, msg, protected_objects): self.protected_objects = protected_objects - super(ProtectedError, self).__init__(msg, protected_objects) + super().__init__(msg, protected_objects) def CASCADE(collector, field, sub_objs, using): diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index a1cec2393a..fcbf867b96 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -157,7 +157,7 @@ class BaseExpression: ``` def override_as_sql(self, compiler, connection): # custom logic - return super(Expression, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) setattr(Expression, 'as_' + connection.vendor, override_as_sql) ``` @@ -351,7 +351,7 @@ class Expression(BaseExpression, Combinable): class CombinedExpression(Expression): def __init__(self, lhs, connector, rhs, output_field=None): - super(CombinedExpression, self).__init__(output_field=output_field) + super().__init__(output_field=output_field) self.connector = connector self.lhs = lhs self.rhs = rhs @@ -437,7 +437,7 @@ class DurationExpression(CombinedExpression): class TemporalSubtraction(CombinedExpression): def __init__(self, lhs, rhs): - super(TemporalSubtraction, self).__init__(lhs, self.SUB, rhs, output_field=fields.DurationField()) + super().__init__(lhs, self.SUB, rhs, output_field=fields.DurationField()) def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) @@ -517,7 +517,7 @@ class Func(Expression): ) ) output_field = extra.pop('output_field', None) - super(Func, self).__init__(output_field=output_field) + super().__init__(output_field=output_field) self.source_expressions = self._parse_expressions(*expressions) self.extra = extra @@ -573,7 +573,7 @@ class Func(Expression): return sql, params def copy(self): - copy = super(Func, self).copy() + copy = super().copy() copy.source_expressions = self.source_expressions[:] copy.extra = self.extra.copy() return copy @@ -592,7 +592,7 @@ class Value(Expression): * output_field: an instance of the model field type that this expression will return, such as IntegerField() or CharField(). """ - super(Value, self).__init__(output_field=output_field) + super().__init__(output_field=output_field) self.value = value def __repr__(self): @@ -617,7 +617,7 @@ class Value(Expression): return '%s', [val] def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - c = super(Value, self).resolve_expression(query, allow_joins, reuse, summarize, for_save) + c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) c.for_save = for_save return c @@ -629,7 +629,7 @@ class DurationValue(Value): def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) if connection.features.has_native_duration_field: - return super(DurationValue, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) return connection.ops.date_interval_sql(self.value) @@ -638,7 +638,7 @@ class RawSQL(Expression): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params - super(RawSQL, self).__init__(output_field=output_field) + super().__init__(output_field=output_field) def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params) @@ -660,7 +660,7 @@ class Star(Expression): class Random(Expression): def __init__(self): - super(Random, self).__init__(output_field=fields.FloatField()) + super().__init__(output_field=fields.FloatField()) def __repr__(self): return "Random()" @@ -676,7 +676,7 @@ class Col(Expression): def __init__(self, alias, target, output_field=None): if output_field is None: output_field = target - super(Col, self).__init__(output_field=output_field) + super().__init__(output_field=output_field) self.alias, self.target = alias, target def __repr__(self): @@ -706,7 +706,7 @@ class Ref(Expression): qs.annotate(sum_cost=Sum('cost')) query. """ def __init__(self, refs, source): - super(Ref, self).__init__() + super().__init__() self.refs, self.source = refs, source def __repr__(self): @@ -740,7 +740,7 @@ class ExpressionWrapper(Expression): """ def __init__(self, expression, output_field): - super(ExpressionWrapper, self).__init__(output_field=output_field) + super().__init__(output_field=output_field) self.expression = expression def set_source_expressions(self, exprs): @@ -764,7 +764,7 @@ class When(Expression): condition, lookups = Q(**lookups), None if condition is None or not isinstance(condition, Q) or lookups: raise TypeError("__init__() takes either a Q object or lookups as keyword arguments") - super(When, self).__init__(output_field=None) + super().__init__(output_field=None) self.condition = condition self.result = self._parse_expressions(then)[0] @@ -833,7 +833,7 @@ class Case(Expression): raise TypeError("Positional arguments must all be When objects.") default = extra.pop('default', None) output_field = extra.pop('output_field', None) - super(Case, self).__init__(output_field) + super().__init__(output_field) self.cases = list(cases) self.default = self._parse_expressions(default)[0] self.extra = extra @@ -860,7 +860,7 @@ class Case(Expression): return c def copy(self): - c = super(Case, self).copy() + c = super().copy() c.cases = c.cases[:] return c @@ -905,10 +905,10 @@ class Subquery(Expression): self.extra = extra if output_field is None and len(self.queryset.query.select) == 1: output_field = self.queryset.query.select[0].field - super(Subquery, self).__init__(output_field) + super().__init__(output_field) def copy(self): - clone = super(Subquery, self).copy() + clone = super().copy() clone.queryset = clone.queryset.all() return clone @@ -985,7 +985,7 @@ class Exists(Subquery): def __init__(self, *args, **kwargs): self.negated = kwargs.pop('negated', False) - super(Exists, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __invert__(self): return type(self)(self.queryset, self.output_field, negated=(not self.negated), **self.extra) @@ -998,10 +998,10 @@ class Exists(Subquery): # As a performance optimization, remove ordering since EXISTS doesn't # care about it, just whether or not a row matches. self.queryset = self.queryset.order_by() - return super(Exists, self).resolve_expression(query, **kwargs) + return super().resolve_expression(query, **kwargs) def as_sql(self, compiler, connection, template=None, **extra_context): - sql, params = super(Exists, self).as_sql(compiler, connection, template, **extra_context) + sql, params = super().as_sql(compiler, connection, template, **extra_context) if self.negated: sql = 'NOT {}'.format(sql) return sql, params diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index fabd291159..bcaf0597a7 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -184,7 +184,7 @@ class Field(RegisterLookupMixin): models. """ if not hasattr(self, 'model'): - return super(Field, self).__str__() + return super().__str__() model = self.model app = model._meta.app_label return '%s.%s.%s' % (app, model._meta.object_name, self.name) @@ -867,10 +867,10 @@ class AutoField(Field): def __init__(self, *args, **kwargs): kwargs['blank'] = True - super(AutoField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def check(self, **kwargs): - errors = super(AutoField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_primary_key()) return errors @@ -887,7 +887,7 @@ class AutoField(Field): return [] def deconstruct(self): - name, path, args, kwargs = super(AutoField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['blank'] kwargs['primary_key'] = True return name, path, args, kwargs @@ -920,14 +920,14 @@ class AutoField(Field): return value def get_prep_value(self, value): - value = super(AutoField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return int(value) def contribute_to_class(self, cls, name, **kwargs): assert not cls._meta.auto_field, "A model can't have more than one AutoField." - super(AutoField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self def formfield(self, **kwargs): @@ -953,10 +953,10 @@ class BooleanField(Field): def __init__(self, *args, **kwargs): kwargs['blank'] = True - super(BooleanField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def check(self, **kwargs): - errors = super(BooleanField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_null(**kwargs)) return errors @@ -974,7 +974,7 @@ class BooleanField(Field): return [] def deconstruct(self): - name, path, args, kwargs = super(BooleanField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['blank'] return name, path, args, kwargs @@ -997,7 +997,7 @@ class BooleanField(Field): ) def get_prep_value(self, value): - value = super(BooleanField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return self.to_python(value) @@ -1011,18 +1011,18 @@ class BooleanField(Field): else: defaults = {'form_class': forms.BooleanField} defaults.update(kwargs) - return super(BooleanField, self).formfield(**defaults) + return super().formfield(**defaults) class CharField(Field): description = _("String (up to %(max_length)s)") def __init__(self, *args, **kwargs): - super(CharField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): - errors = super(CharField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_max_length_attribute(**kwargs)) return errors @@ -1055,7 +1055,7 @@ class CharField(Field): return force_text(value) def get_prep_value(self, value): - value = super(CharField, self).get_prep_value(value) + value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): @@ -1067,7 +1067,7 @@ class CharField(Field): if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults['empty_value'] = None defaults.update(kwargs) - return super(CharField, self).formfield(**defaults) + return super().formfield(**defaults) class CommaSeparatedIntegerField(CharField): @@ -1089,7 +1089,7 @@ class CommaSeparatedIntegerField(CharField): class DateTimeCheckMixin: def check(self, **kwargs): - errors = super(DateTimeCheckMixin, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_mutually_exclusive_options()) errors.extend(self._check_fix_default_value()) return errors @@ -1133,7 +1133,7 @@ class DateField(DateTimeCheckMixin, Field): if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True - super(DateField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ @@ -1179,7 +1179,7 @@ class DateField(DateTimeCheckMixin, Field): return [] def deconstruct(self): - name, path, args, kwargs = super(DateField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.auto_now: kwargs['auto_now'] = True if self.auto_now_add: @@ -1228,10 +1228,10 @@ class DateField(DateTimeCheckMixin, Field): setattr(model_instance, self.attname, value) return value else: - return super(DateField, self).pre_save(model_instance, add) + return super().pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): - super(DateField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, 'get_next_by_%s' % self.name, @@ -1243,7 +1243,7 @@ class DateField(DateTimeCheckMixin, Field): ) def get_prep_value(self, value): - value = super(DateField, self).get_prep_value(value) + value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): @@ -1259,7 +1259,7 @@ class DateField(DateTimeCheckMixin, Field): def formfield(self, **kwargs): defaults = {'form_class': forms.DateField} defaults.update(kwargs) - return super(DateField, self).formfield(**defaults) + return super().formfield(**defaults) class DateTimeField(DateField): @@ -1380,13 +1380,13 @@ class DateTimeField(DateField): setattr(model_instance, self.attname, value) return value else: - return super(DateTimeField, self).pre_save(model_instance, add) + return super().pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO def get_prep_value(self, value): - value = super(DateTimeField, self).get_prep_value(value) + value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local @@ -1417,7 +1417,7 @@ class DateTimeField(DateField): def formfield(self, **kwargs): defaults = {'form_class': forms.DateTimeField} defaults.update(kwargs) - return super(DateTimeField, self).formfield(**defaults) + return super().formfield(**defaults) class DecimalField(Field): @@ -1430,10 +1430,10 @@ class DecimalField(Field): def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places - super(DecimalField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): - errors = super(DecimalField, self).check(**kwargs) + errors = super().check(**kwargs) digits_errors = self._check_decimal_places() digits_errors.extend(self._check_max_digits()) @@ -1504,12 +1504,12 @@ class DecimalField(Field): @cached_property def validators(self): - return super(DecimalField, self).validators + [ + return super().validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ] def deconstruct(self): - name, path, args, kwargs = super(DecimalField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.max_digits is not None: kwargs['max_digits'] = self.max_digits if self.decimal_places is not None: @@ -1555,7 +1555,7 @@ class DecimalField(Field): return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places) def get_prep_value(self, value): - value = super(DecimalField, self).get_prep_value(value) + value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): @@ -1565,7 +1565,7 @@ class DecimalField(Field): 'form_class': forms.DecimalField, } defaults.update(kwargs) - return super(DecimalField, self).formfield(**defaults) + return super().formfield(**defaults) class DurationField(Field): @@ -1615,7 +1615,7 @@ class DurationField(Field): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) - return converters + super(DurationField, self).get_db_converters(connection) + return converters + super().get_db_converters(connection) def value_to_string(self, obj): val = self.value_from_object(obj) @@ -1626,7 +1626,7 @@ class DurationField(Field): 'form_class': forms.DurationField, } defaults.update(kwargs) - return super(DurationField, self).formfield(**defaults) + return super().formfield(**defaults) class EmailField(CharField): @@ -1636,10 +1636,10 @@ class EmailField(CharField): def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs['max_length'] = kwargs.get('max_length', 254) - super(EmailField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(EmailField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs @@ -1651,7 +1651,7 @@ class EmailField(CharField): 'form_class': forms.EmailField, } defaults.update(kwargs) - return super(EmailField, self).formfield(**defaults) + return super().formfield(**defaults) class FilePathField(Field): @@ -1662,10 +1662,10 @@ class FilePathField(Field): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs['max_length'] = kwargs.get('max_length', 100) - super(FilePathField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): - errors = super(FilePathField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_allowing_files_or_folders(**kwargs)) return errors @@ -1681,7 +1681,7 @@ class FilePathField(Field): return [] def deconstruct(self): - name, path, args, kwargs = super(FilePathField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.path != '': kwargs['path'] = self.path if self.match is not None: @@ -1697,7 +1697,7 @@ class FilePathField(Field): return name, path, args, kwargs def get_prep_value(self, value): - value = super(FilePathField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return str(value) @@ -1712,7 +1712,7 @@ class FilePathField(Field): 'allow_folders': self.allow_folders, } defaults.update(kwargs) - return super(FilePathField, self).formfield(**defaults) + return super().formfield(**defaults) def get_internal_type(self): return "FilePathField" @@ -1726,7 +1726,7 @@ class FloatField(Field): description = _("Floating point number") def get_prep_value(self, value): - value = super(FloatField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return float(value) @@ -1749,7 +1749,7 @@ class FloatField(Field): def formfield(self, **kwargs): defaults = {'form_class': forms.FloatField} defaults.update(kwargs) - return super(FloatField, self).formfield(**defaults) + return super().formfield(**defaults) class IntegerField(Field): @@ -1760,7 +1760,7 @@ class IntegerField(Field): description = _("Integer") def check(self, **kwargs): - errors = super(IntegerField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_max_length_warning()) return errors @@ -1780,7 +1780,7 @@ class IntegerField(Field): def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. - validators_ = super(IntegerField, self).validators + validators_ = super().validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None: @@ -1798,7 +1798,7 @@ class IntegerField(Field): return validators_ def get_prep_value(self, value): - value = super(IntegerField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return int(value) @@ -1821,7 +1821,7 @@ class IntegerField(Field): def formfield(self, **kwargs): defaults = {'form_class': forms.IntegerField} defaults.update(kwargs) - return super(IntegerField, self).formfield(**defaults) + return super().formfield(**defaults) class BigIntegerField(IntegerField): @@ -1836,7 +1836,7 @@ class BigIntegerField(IntegerField): defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1, 'max_value': BigIntegerField.MAX_BIGINT} defaults.update(kwargs) - return super(BigIntegerField, self).formfield(**defaults) + return super().formfield(**defaults) class IPAddressField(Field): @@ -1853,15 +1853,15 @@ class IPAddressField(Field): def __init__(self, *args, **kwargs): kwargs['max_length'] = 15 - super(IPAddressField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(IPAddressField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['max_length'] return name, path, args, kwargs def get_prep_value(self, value): - value = super(IPAddressField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return str(value) @@ -1883,11 +1883,10 @@ class GenericIPAddressField(Field): validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages['invalid'] = invalid_error_message kwargs['max_length'] = 39 - super(GenericIPAddressField, self).__init__(verbose_name, name, *args, - **kwargs) + super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): - errors = super(GenericIPAddressField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_blank_and_null_values(**kwargs)) return errors @@ -1904,7 +1903,7 @@ class GenericIPAddressField(Field): return [] def deconstruct(self): - name, path, args, kwargs = super(GenericIPAddressField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.unpack_ipv4 is not False: kwargs['unpack_ipv4'] = self.unpack_ipv4 if self.protocol != "both": @@ -1932,7 +1931,7 @@ class GenericIPAddressField(Field): return connection.ops.adapt_ipaddressfield_value(value) def get_prep_value(self, value): - value = super(GenericIPAddressField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None if value and ':' in value: @@ -1948,7 +1947,7 @@ class GenericIPAddressField(Field): 'form_class': forms.GenericIPAddressField, } defaults.update(kwargs) - return super(GenericIPAddressField, self).formfield(**defaults) + return super().formfield(**defaults) class NullBooleanField(Field): @@ -1961,10 +1960,10 @@ class NullBooleanField(Field): def __init__(self, *args, **kwargs): kwargs['null'] = True kwargs['blank'] = True - super(NullBooleanField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(NullBooleanField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['null'] del kwargs['blank'] return name, path, args, kwargs @@ -1990,7 +1989,7 @@ class NullBooleanField(Field): ) def get_prep_value(self, value): - value = super(NullBooleanField, self).get_prep_value(value) + value = super().get_prep_value(value) if value is None: return None return self.to_python(value) @@ -1998,7 +1997,7 @@ class NullBooleanField(Field): def formfield(self, **kwargs): defaults = {'form_class': forms.NullBooleanField} defaults.update(kwargs) - return super(NullBooleanField, self).formfield(**defaults) + return super().formfield(**defaults) class PositiveIntegerRelDbTypeMixin: @@ -2027,7 +2026,7 @@ class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): def formfield(self, **kwargs): defaults = {'min_value': 0} defaults.update(kwargs) - return super(PositiveIntegerField, self).formfield(**defaults) + return super().formfield(**defaults) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): @@ -2039,7 +2038,7 @@ class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): def formfield(self, **kwargs): defaults = {'min_value': 0} defaults.update(kwargs) - return super(PositiveSmallIntegerField, self).formfield(**defaults) + return super().formfield(**defaults) class SlugField(CharField): @@ -2054,10 +2053,10 @@ class SlugField(CharField): self.allow_unicode = kwargs.pop('allow_unicode', False) if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] - super(SlugField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(SlugField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs['max_length'] if self.db_index is False: @@ -2074,7 +2073,7 @@ class SlugField(CharField): def formfield(self, **kwargs): defaults = {'form_class': forms.SlugField, 'allow_unicode': self.allow_unicode} defaults.update(kwargs) - return super(SlugField, self).formfield(**defaults) + return super().formfield(**defaults) class SmallIntegerField(IntegerField): @@ -2096,7 +2095,7 @@ class TextField(Field): return force_text(value) def get_prep_value(self, value): - value = super(TextField, self).get_prep_value(value) + value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): @@ -2105,7 +2104,7 @@ class TextField(Field): # the value in the form field (to pass into widget for example). defaults = {'max_length': self.max_length, 'widget': forms.Textarea} defaults.update(kwargs) - return super(TextField, self).formfield(**defaults) + return super().formfield(**defaults) class TimeField(DateTimeCheckMixin, Field): @@ -2124,7 +2123,7 @@ class TimeField(DateTimeCheckMixin, Field): if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True - super(TimeField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ @@ -2173,7 +2172,7 @@ class TimeField(DateTimeCheckMixin, Field): return [] def deconstruct(self): - name, path, args, kwargs = super(TimeField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: @@ -2220,10 +2219,10 @@ class TimeField(DateTimeCheckMixin, Field): setattr(model_instance, self.attname, value) return value else: - return super(TimeField, self).pre_save(model_instance, add) + return super().pre_save(model_instance, add) def get_prep_value(self, value): - value = super(TimeField, self).get_prep_value(value) + value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): @@ -2239,7 +2238,7 @@ class TimeField(DateTimeCheckMixin, Field): def formfield(self, **kwargs): defaults = {'form_class': forms.TimeField} defaults.update(kwargs) - return super(TimeField, self).formfield(**defaults) + return super().formfield(**defaults) class URLField(CharField): @@ -2248,10 +2247,10 @@ class URLField(CharField): def __init__(self, verbose_name=None, name=None, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 200) - super(URLField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(URLField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs['max_length'] return name, path, args, kwargs @@ -2263,7 +2262,7 @@ class URLField(CharField): 'form_class': forms.URLField, } defaults.update(kwargs) - return super(URLField, self).formfield(**defaults) + return super().formfield(**defaults) class BinaryField(Field): @@ -2272,12 +2271,12 @@ class BinaryField(Field): def __init__(self, *args, **kwargs): kwargs['editable'] = False - super(BinaryField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def deconstruct(self): - name, path, args, kwargs = super(BinaryField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['editable'] return name, path, args, kwargs @@ -2290,13 +2289,13 @@ class BinaryField(Field): def get_default(self): if self.has_default() and not callable(self.default): return self.default - default = super(BinaryField, self).get_default() + default = super().get_default() if default == '': return b'' return default def get_db_prep_value(self, value, connection, prepared=False): - value = super(BinaryField, self).get_db_prep_value(value, connection, prepared) + value = super().get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value @@ -2321,10 +2320,10 @@ class UUIDField(Field): def __init__(self, verbose_name=None, **kwargs): kwargs['max_length'] = 32 - super(UUIDField, self).__init__(verbose_name, **kwargs) + super().__init__(verbose_name, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(UUIDField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['max_length'] return name, path, args, kwargs @@ -2358,4 +2357,4 @@ class UUIDField(Field): 'form_class': forms.UUIDField, } defaults.update(kwargs) - return super(UUIDField, self).formfield(**defaults) + return super().formfield(**defaults) diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py index 4e678ea672..60ac33ff63 100644 --- a/django/db/models/fields/files.py +++ b/django/db/models/fields/files.py @@ -15,7 +15,7 @@ from django.utils.translation import ugettext_lazy as _ class FieldFile(File): def __init__(self, instance, field, name): - super(FieldFile, self).__init__(None, name) + super().__init__(None, name) self.instance = instance self.field = field self.storage = field.storage @@ -228,10 +228,10 @@ class FileField(Field): self.upload_to = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) - super(FileField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): - errors = super(FileField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_primary_key()) errors.extend(self._check_upload_to()) return errors @@ -263,7 +263,7 @@ class FileField(Field): return [] def deconstruct(self): - name, path, args, kwargs = super(FileField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 100: del kwargs["max_length"] kwargs['upload_to'] = self.upload_to @@ -276,7 +276,7 @@ class FileField(Field): def get_prep_value(self, value): "Returns field's value prepared for saving into a database." - value = super(FileField, self).get_prep_value(value) + value = super().get_prep_value(value) # Need to convert File objects provided via a form to string for database insertion if value is None: return None @@ -284,14 +284,14 @@ class FileField(Field): def pre_save(self, model_instance, add): "Returns field's value just before saving." - file = super(FileField, self).pre_save(model_instance, add) + file = super().pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file.file, save=False) return file def contribute_to_class(self, cls, name, **kwargs): - super(FileField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) setattr(cls, self.name, self.descriptor_class(self)) def generate_filename(self, instance, filename): @@ -330,7 +330,7 @@ class FileField(Field): if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) - return super(FileField, self).formfield(**defaults) + return super().formfield(**defaults) class ImageFileDescriptor(FileDescriptor): @@ -340,7 +340,7 @@ class ImageFileDescriptor(FileDescriptor): """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) - super(ImageFileDescriptor, self).__set__(instance, value) + super().__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if @@ -360,7 +360,7 @@ class ImageFieldFile(ImageFile, FieldFile): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache - super(ImageFieldFile, self).delete(save) + super().delete(save) class ImageField(FileField): @@ -371,10 +371,10 @@ class ImageField(FileField): def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field - super(ImageField, self).__init__(verbose_name, name, **kwargs) + super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): - errors = super(ImageField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_image_library_installed()) return errors @@ -395,7 +395,7 @@ class ImageField(FileField): return [] def deconstruct(self): - name, path, args, kwargs = super(ImageField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if self.width_field: kwargs['width_field'] = self.width_field if self.height_field: @@ -403,7 +403,7 @@ class ImageField(FileField): return name, path, args, kwargs def contribute_to_class(self, cls, name, **kwargs): - super(ImageField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. @@ -471,4 +471,4 @@ class ImageField(FileField): def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) - return super(ImageField, self).formfield(**defaults) + return super().formfield(**defaults) diff --git a/django/db/models/fields/proxy.py b/django/db/models/fields/proxy.py index 19beb89011..f89cd3db46 100644 --- a/django/db/models/fields/proxy.py +++ b/django/db/models/fields/proxy.py @@ -15,9 +15,9 @@ class OrderWrt(fields.IntegerField): def __init__(self, *args, **kwargs): kwargs['name'] = '_order' kwargs['editable'] = False - super(OrderWrt, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(OrderWrt, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['editable'] return name, path, args, kwargs diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 855bf38ea0..dd84d780fb 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -97,7 +97,7 @@ class RelatedField(Field): return self.remote_field.model def check(self, **kwargs): - errors = super(RelatedField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_related_name_is_valid()) errors.extend(self._check_related_query_name_is_valid()) errors.extend(self._check_relation_model_exists()) @@ -294,7 +294,7 @@ class RelatedField(Field): def contribute_to_class(self, cls, name, private_only=False, **kwargs): - super(RelatedField, self).contribute_to_class(cls, name, private_only=private_only, **kwargs) + super().contribute_to_class(cls, name, private_only=private_only, **kwargs) self.opts = cls._meta @@ -412,7 +412,7 @@ class RelatedField(Field): 'limit_choices_to': limit_choices_to, }) defaults.update(kwargs) - return super(RelatedField, self).formfield(**defaults) + return super().formfield(**defaults) def related_query_name(self): """ @@ -464,14 +464,14 @@ class ForeignObject(RelatedField): on_delete=on_delete, ) - super(ForeignObject, self).__init__(rel=rel, **kwargs) + super().__init__(rel=rel, **kwargs) self.from_fields = from_fields self.to_fields = to_fields self.swappable = swappable def check(self, **kwargs): - errors = super(ForeignObject, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_to_fields_exist()) errors.extend(self._check_unique_target()) return errors @@ -555,7 +555,7 @@ class ForeignObject(RelatedField): return [] def deconstruct(self): - name, path, args, kwargs = super(ForeignObject, self).deconstruct() + name, path, args, kwargs = super().deconstruct() kwargs['on_delete'] = self.remote_field.on_delete kwargs['from_fields'] = self.from_fields kwargs['to_fields'] = self.to_fields @@ -653,7 +653,7 @@ class ForeignObject(RelatedField): return tuple(ret) def get_attname_column(self): - attname, column = super(ForeignObject, self).get_attname_column() + attname, column = super().get_attname_column() return attname, None def get_joining_columns(self, reverse_join=False): @@ -718,7 +718,7 @@ class ForeignObject(RelatedField): return cls.merge_dicts(class_lookups) def contribute_to_class(self, cls, name, private_only=False, **kwargs): - super(ForeignObject, self).contribute_to_class(cls, name, private_only=private_only, **kwargs) + super().contribute_to_class(cls, name, private_only=private_only, **kwargs) setattr(cls, self.name, self.forward_related_accessor_class(self)) def contribute_to_related_class(self, cls, related): @@ -795,13 +795,12 @@ class ForeignKey(ForeignObject): kwargs['db_index'] = kwargs.get('db_index', True) - super(ForeignKey, self).__init__( - to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs) + super().__init__(to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs) self.db_constraint = db_constraint def check(self, **kwargs): - errors = super(ForeignKey, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_on_delete()) errors.extend(self._check_unique()) return errors @@ -840,7 +839,7 @@ class ForeignKey(ForeignObject): ] if self.unique else [] def deconstruct(self): - name, path, args, kwargs = super(ForeignKey, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['to_fields'] del kwargs['from_fields'] # Handle the simpler arguments @@ -873,7 +872,7 @@ class ForeignKey(ForeignObject): def validate(self, value, model_instance): if self.remote_field.parent_link: return - super(ForeignKey, self).validate(value, model_instance) + super().validate(value, model_instance) if value is None: return @@ -902,7 +901,7 @@ class ForeignKey(ForeignObject): def get_default(self): "Here we check if the default value is an object and return the to_field if so." - field_default = super(ForeignKey, self).get_default() + field_default = super().get_default() if isinstance(field_default, self.remote_field.model): return getattr(field_default, self.target_field.attname) return field_default @@ -919,7 +918,7 @@ class ForeignKey(ForeignObject): return self.target_field.get_db_prep_value(value, connection, prepared) def contribute_to_related_class(self, cls, related): - super(ForeignKey, self).contribute_to_related_class(cls, related) + super().contribute_to_related_class(cls, related) if self.remote_field.field_name is None: self.remote_field.field_name = cls._meta.pk.name @@ -935,7 +934,7 @@ class ForeignKey(ForeignObject): 'to_field_name': self.remote_field.field_name, } defaults.update(kwargs) - return super(ForeignKey, self).formfield(**defaults) + return super().formfield(**defaults) def db_check(self, connection): return [] @@ -952,13 +951,13 @@ class ForeignKey(ForeignObject): return value def get_db_converters(self, connection): - converters = super(ForeignKey, self).get_db_converters(connection) + converters = super().get_db_converters(connection) if connection.features.interprets_empty_strings_as_nulls: converters += [self.convert_empty_strings] return converters def get_col(self, alias, output_field=None): - return super(ForeignKey, self).get_col(alias, output_field or self.target_field) + return super().get_col(alias, output_field or self.target_field) class OneToOneField(ForeignKey): @@ -983,10 +982,10 @@ class OneToOneField(ForeignKey): def __init__(self, to, on_delete, to_field=None, **kwargs): kwargs['unique'] = True - super(OneToOneField, self).__init__(to, on_delete, to_field=to_field, **kwargs) + super().__init__(to, on_delete, to_field=to_field, **kwargs) def deconstruct(self): - name, path, args, kwargs = super(OneToOneField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() if "unique" in kwargs: del kwargs['unique'] return name, path, args, kwargs @@ -994,7 +993,7 @@ class OneToOneField(ForeignKey): def formfield(self, **kwargs): if self.remote_field.parent_link: return None - return super(OneToOneField, self).formfield(**kwargs) + return super().formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.remote_field.model): @@ -1107,13 +1106,13 @@ class ManyToManyField(RelatedField): ) self.has_null_arg = 'null' in kwargs - super(ManyToManyField, self).__init__(**kwargs) + super().__init__(**kwargs) self.db_table = db_table self.swappable = swappable def check(self, **kwargs): - errors = super(ManyToManyField, self).check(**kwargs) + errors = super().check(**kwargs) errors.extend(self._check_unique(**kwargs)) errors.extend(self._check_relationship_model(**kwargs)) errors.extend(self._check_ignored_options(**kwargs)) @@ -1396,7 +1395,7 @@ class ManyToManyField(RelatedField): return [] def deconstruct(self): - name, path, args, kwargs = super(ManyToManyField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() # Handle the simpler arguments. if self.db_table is not None: kwargs['db_table'] = self.db_table @@ -1558,7 +1557,7 @@ class ManyToManyField(RelatedField): # clashes between multiple m2m fields with related_name == '+'. self.remote_field.related_name = "_%s_%s_+" % (cls.__name__.lower(), name) - super(ManyToManyField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or @@ -1624,7 +1623,7 @@ class ManyToManyField(RelatedField): if callable(initial): initial = initial() defaults['initial'] = [i._get_pk_val() for i in initial] - return super(ManyToManyField, self).formfield(**defaults) + return super().formfield(**defaults) def db_check(self, connection): return None diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py index a878a79acd..b3e87cd482 100644 --- a/django/db/models/fields/related_descriptors.py +++ b/django/db/models/fields/related_descriptors.py @@ -272,7 +272,7 @@ class ForwardOneToOneDescriptor(ForwardManyToOneDescriptor): if not any(field in fields for field in deferred): kwargs = {field: getattr(instance, field) for field in fields} return rel_model(**kwargs) - return super(ForwardOneToOneDescriptor, self).get_object(instance) + return super().get_object(instance) class ReverseOneToOneDescriptor: @@ -502,7 +502,7 @@ def create_reverse_many_to_one_manager(superclass, rel): class RelatedManager(superclass): def __init__(self, instance): - super(RelatedManager, self).__init__() + super().__init__() self.instance = instance self.model = rel.related_model @@ -545,12 +545,12 @@ def create_reverse_many_to_one_manager(superclass, rel): try: return self.instance._prefetched_objects_cache[self.field.related_query_name()] except (AttributeError, KeyError): - queryset = super(RelatedManager, self).get_queryset() + queryset = super().get_queryset() return self._apply_rel_filters(queryset) def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: - queryset = super(RelatedManager, self).get_queryset() + queryset = super().get_queryset() queryset._add_hints(instance=instances[0]) queryset = queryset.using(queryset._db or self._db) @@ -708,7 +708,7 @@ class ManyToManyDescriptor(ReverseManyToOneDescriptor): """ def __init__(self, rel, reverse=False): - super(ManyToManyDescriptor, self).__init__(rel) + super().__init__(rel) self.reverse = reverse @@ -746,7 +746,7 @@ def create_forward_many_to_many_manager(superclass, rel, reverse): class ManyRelatedManager(superclass): def __init__(self, instance=None): - super(ManyRelatedManager, self).__init__() + super().__init__() self.instance = instance @@ -834,12 +834,12 @@ def create_forward_many_to_many_manager(superclass, rel, reverse): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): - queryset = super(ManyRelatedManager, self).get_queryset() + queryset = super().get_queryset() return self._apply_rel_filters(queryset) def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: - queryset = super(ManyRelatedManager, self).get_queryset() + queryset = super().get_queryset() queryset._add_hints(instance=instances[0]) queryset = queryset.using(queryset._db or self._db) @@ -914,7 +914,7 @@ def create_forward_many_to_many_manager(superclass, rel, reverse): model=self.model, pk_set=None, using=db, ) self._remove_prefetched_objects() - filters = self._build_remove_filters(super(ManyRelatedManager, self).get_queryset().using(db)) + filters = self._build_remove_filters(super().get_queryset().using(db)) self.through._default_manager.using(db).filter(filters).delete() signals.m2m_changed.send( @@ -1091,7 +1091,7 @@ def create_forward_many_to_many_manager(superclass, rel, reverse): instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids, using=db, ) - target_model_qs = super(ManyRelatedManager, self).get_queryset() + target_model_qs = super().get_queryset() if target_model_qs._has_filters(): old_vals = target_model_qs.using(db).filter(**{ '%s__in' % self.target_field.target_field.attname: old_ids}) diff --git a/django/db/models/fields/related_lookups.py b/django/db/models/fields/related_lookups.py index bc80c7cb02..8063ea801a 100644 --- a/django/db/models/fields/related_lookups.py +++ b/django/db/models/fields/related_lookups.py @@ -54,7 +54,7 @@ class RelatedIn(In): # only one as we don't get to the direct value branch otherwise. target_field = self.lhs.output_field.get_path_info()[-1].target_fields[-1] self.rhs = [target_field.get_prep_value(v) for v in self.rhs] - return super(RelatedIn, self).get_prep_lookup() + return super().get_prep_lookup() def as_sql(self, compiler, connection): if isinstance(self.lhs, MultiColSource): @@ -91,7 +91,7 @@ class RelatedIn(In): else: target_field = self.lhs.field.target_field.name self.rhs.add_fields([target_field], True) - return super(RelatedIn, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class RelatedLookupMixin: @@ -109,7 +109,7 @@ class RelatedLookupMixin: target_field = self.lhs.output_field.get_path_info()[-1].target_fields[-1] self.rhs = target_field.get_prep_value(self.rhs) - return super(RelatedLookupMixin, self).get_prep_lookup() + return super().get_prep_lookup() def as_sql(self, compiler, connection): if isinstance(self.lhs, MultiColSource): @@ -122,7 +122,7 @@ class RelatedLookupMixin: root_constraint.add( lookup_class(target.get_col(self.lhs.alias, source), val), AND) return root_constraint.as_sql(compiler, connection) - return super(RelatedLookupMixin, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) class RelatedExact(RelatedLookupMixin, Exact): diff --git a/django/db/models/fields/reverse_related.py b/django/db/models/fields/reverse_related.py index 4e835e8302..3d5439ab84 100644 --- a/django/db/models/fields/reverse_related.py +++ b/django/db/models/fields/reverse_related.py @@ -187,7 +187,7 @@ class ManyToOneRel(ForeignObjectRel): def __init__(self, field, to, field_name, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None): - super(ManyToOneRel, self).__init__( + super().__init__( field, to, related_name=related_name, related_query_name=related_query_name, @@ -226,7 +226,7 @@ class OneToOneRel(ManyToOneRel): def __init__(self, field, to, field_name, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None): - super(OneToOneRel, self).__init__( + super().__init__( field, to, field_name, related_name=related_name, related_query_name=related_query_name, @@ -249,7 +249,7 @@ class ManyToManyRel(ForeignObjectRel): def __init__(self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=True, through=None, through_fields=None, db_constraint=True): - super(ManyToManyRel, self).__init__( + super().__init__( field, to, related_name=related_name, related_query_name=related_query_name, diff --git a/django/db/models/functions/base.py b/django/db/models/functions/base.py index ca73340b85..e9bf01ff0d 100644 --- a/django/db/models/functions/base.py +++ b/django/db/models/functions/base.py @@ -18,12 +18,12 @@ class Cast(Func): } def __init__(self, expression, output_field): - super(Cast, self).__init__(expression, output_field=output_field) + super().__init__(expression, output_field=output_field) def as_sql(self, compiler, connection, **extra_context): if 'db_type' not in extra_context: extra_context['db_type'] = self._output_field.db_type(connection) - return super(Cast, self).as_sql(compiler, connection, **extra_context) + return super().as_sql(compiler, connection, **extra_context) def as_mysql(self, compiler, connection): extra_context = {} @@ -46,7 +46,7 @@ class Coalesce(Func): def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError('Coalesce must take at least two expressions') - super(Coalesce, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) def as_oracle(self, compiler, connection): # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert @@ -72,7 +72,7 @@ class ConcatPair(Func): function = 'CONCAT' def __init__(self, left, right, **extra): - super(ConcatPair, self).__init__(left, right, **extra) + super().__init__(left, right, **extra) def as_sqlite(self, compiler, connection): coalesced = self.coalesce() @@ -82,7 +82,7 @@ class ConcatPair(Func): def as_mysql(self, compiler, connection): # Use CONCAT_WS with an empty separator so that NULLs are ignored. - return super(ConcatPair, self).as_sql( + return super().as_sql( compiler, connection, function='CONCAT_WS', template="%(function)s('', %(expressions)s)" ) @@ -109,7 +109,7 @@ class Concat(Func): if len(expressions) < 2: raise ValueError('Concat must take at least two expressions') paired = self._paired(expressions) - super(Concat, self).__init__(paired, **extra) + super().__init__(paired, **extra) def _paired(self, expressions): # wrap pairs of expressions in successive concat functions @@ -133,11 +133,11 @@ class Greatest(Func): def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError('Greatest must take at least two expressions') - super(Greatest, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection): """Use the MAX function on SQLite.""" - return super(Greatest, self).as_sql(compiler, connection, function='MAX') + return super().as_sql(compiler, connection, function='MAX') class Least(Func): @@ -153,11 +153,11 @@ class Least(Func): def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError('Least must take at least two expressions') - super(Least, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection): """Use the MIN function on SQLite.""" - return super(Least, self).as_sql(compiler, connection, function='MIN') + return super().as_sql(compiler, connection, function='MIN') class Length(Transform): @@ -167,10 +167,10 @@ class Length(Transform): def __init__(self, expression, **extra): output_field = extra.pop('output_field', fields.IntegerField()) - super(Length, self).__init__(expression, output_field=output_field, **extra) + super().__init__(expression, output_field=output_field, **extra) def as_mysql(self, compiler, connection): - return super(Length, self).as_sql(compiler, connection, function='CHAR_LENGTH') + return super().as_sql(compiler, connection, function='CHAR_LENGTH') class Lower(Transform): @@ -184,7 +184,7 @@ class Now(Func): def __init__(self, output_field=None, **extra): if output_field is None: output_field = fields.DateTimeField() - super(Now, self).__init__(output_field=output_field, **extra) + super().__init__(output_field=output_field, **extra) def as_postgresql(self, compiler, connection): # Postgres' CURRENT_TIMESTAMP means "the time at the start of the @@ -211,13 +211,13 @@ class Substr(Func): if not hasattr(length, 'resolve_expression'): length = Value(length) expressions.append(length) - super(Substr, self).__init__(*expressions, **extra) + super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection): - return super(Substr, self).as_sql(compiler, connection, function='SUBSTR') + return super().as_sql(compiler, connection, function='SUBSTR') def as_oracle(self, compiler, connection): - return super(Substr, self).as_sql(compiler, connection, function='SUBSTR') + return super().as_sql(compiler, connection, function='SUBSTR') class Upper(Transform): diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py index 8bfd8cafef..19afc271b5 100644 --- a/django/db/models/functions/datetime.py +++ b/django/db/models/functions/datetime.py @@ -37,7 +37,7 @@ class Extract(TimezoneMixin, Transform): if self.lookup_name is None: raise ValueError('lookup_name must be provided') self.tzinfo = tzinfo - super(Extract, self).__init__(expression, **extra) + super().__init__(expression, **extra) def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) @@ -57,7 +57,7 @@ class Extract(TimezoneMixin, Transform): return sql, params def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - copy = super(Extract, self).resolve_expression(query, allow_joins, reuse, summarize, for_save) + copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) field = copy.lhs.output_field if not isinstance(field, (DateField, DateTimeField, TimeField)): raise ValueError('Extract input expression must be DateField, DateTimeField, or TimeField.') @@ -142,7 +142,7 @@ class TruncBase(TimezoneMixin, Transform): def __init__(self, expression, output_field=None, tzinfo=None, **extra): self.tzinfo = tzinfo - super(TruncBase, self).__init__(expression, output_field=output_field, **extra) + super().__init__(expression, output_field=output_field, **extra) def as_sql(self, compiler, connection): inner_sql, inner_params = compiler.compile(self.lhs) @@ -162,7 +162,7 @@ class TruncBase(TimezoneMixin, Transform): return sql, inner_params + params def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): - copy = super(TruncBase, self).resolve_expression(query, allow_joins, reuse, summarize, for_save) + copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) field = copy.lhs.output_field # DateTimeField is a subclass of DateField so this works for both. assert isinstance(field, (DateField, TimeField)), ( @@ -210,7 +210,7 @@ class Trunc(TruncBase): def __init__(self, expression, kind, output_field=None, tzinfo=None, **extra): self.kind = kind - super(Trunc, self).__init__(expression, output_field=output_field, tzinfo=tzinfo, **extra) + super().__init__(expression, output_field=output_field, tzinfo=tzinfo, **extra) class TruncYear(TruncBase): diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 1536ecdc63..d96c4468f5 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -153,8 +153,7 @@ class Transform(RegisterLookupMixin, Func): class BuiltinLookup(Lookup): def process_lhs(self, compiler, connection, lhs=None): - lhs_sql, params = super(BuiltinLookup, self).process_lhs( - compiler, connection, lhs) + lhs_sql, params = super().process_lhs(compiler, connection, lhs) field_internal_type = self.lhs.output_field.get_internal_type() db_type = self.lhs.output_field.db_type(connection=connection) lhs_sql = connection.ops.field_cast_sql( @@ -223,7 +222,7 @@ class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin): # to prepare/transform those values. return self.batch_process_rhs(compiler, connection) else: - return super(FieldGetDbPrepValueIterableMixin, self).process_rhs(compiler, connection) + return super().process_rhs(compiler, connection) def resolve_expression_parameter(self, compiler, connection, sql, param): params = [param] @@ -234,7 +233,7 @@ class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin): return sql, params def batch_process_rhs(self, compiler, connection, rhs=None): - pre_processed = super(FieldGetDbPrepValueIterableMixin, self).batch_process_rhs(compiler, connection, rhs) + pre_processed = super().batch_process_rhs(compiler, connection, rhs) # The params list may contain expressions which compile to a # sql/param pair. Zip them to get sql and param pairs that refer to the # same argument and attempt to replace them with the result of @@ -258,7 +257,7 @@ class IExact(BuiltinLookup): prepare_rhs = False def process_rhs(self, qn, connection): - rhs, params = super(IExact, self).process_rhs(qn, connection) + rhs, params = super().process_rhs(qn, connection) if params: params[0] = connection.ops.prep_for_iexact_query(params[0]) return rhs, params @@ -292,7 +291,7 @@ class IntegerFieldFloatRounding: def get_prep_lookup(self): if isinstance(self.rhs, float): self.rhs = math.ceil(self.rhs) - return super(IntegerFieldFloatRounding, self).get_prep_lookup() + return super().get_prep_lookup() @IntegerField.register_lookup @@ -366,7 +365,7 @@ class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup): placeholder = '(' + ', '.join(sqls) + ')' return (placeholder, sqls_params) else: - return super(In, self).process_rhs(compiler, connection) + return super().process_rhs(compiler, connection) def get_rhs_op(self, connection, rhs): return 'IN %s' % rhs @@ -375,7 +374,7 @@ class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup): max_in_list_size = connection.ops.max_in_list_size() if self.rhs_is_direct_value() and max_in_list_size and len(self.rhs) > max_in_list_size: return self.split_parameter_list_as_sql(compiler, connection) - return super(In, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) def split_parameter_list_as_sql(self, compiler, connection): # This is a special case for databases which limit the number of @@ -416,7 +415,7 @@ class PatternLookup(BuiltinLookup): pattern = connection.pattern_ops[self.lookup_name].format(connection.pattern_esc) return pattern.format(rhs) else: - return super(PatternLookup, self).get_rhs_op(connection, rhs) + return super().get_rhs_op(connection, rhs) @Field.register_lookup @@ -425,7 +424,7 @@ class Contains(PatternLookup): prepare_rhs = False def process_rhs(self, qn, connection): - rhs, params = super(Contains, self).process_rhs(qn, connection) + rhs, params = super().process_rhs(qn, connection) if params and not self.bilateral_transforms: params[0] = "%%%s%%" % connection.ops.prep_for_like_query(params[0]) return rhs, params @@ -443,7 +442,7 @@ class StartsWith(PatternLookup): prepare_rhs = False def process_rhs(self, qn, connection): - rhs, params = super(StartsWith, self).process_rhs(qn, connection) + rhs, params = super().process_rhs(qn, connection) if params and not self.bilateral_transforms: params[0] = "%s%%" % connection.ops.prep_for_like_query(params[0]) return rhs, params @@ -455,7 +454,7 @@ class IStartsWith(PatternLookup): prepare_rhs = False def process_rhs(self, qn, connection): - rhs, params = super(IStartsWith, self).process_rhs(qn, connection) + rhs, params = super().process_rhs(qn, connection) if params and not self.bilateral_transforms: params[0] = "%s%%" % connection.ops.prep_for_like_query(params[0]) return rhs, params @@ -467,7 +466,7 @@ class EndsWith(PatternLookup): prepare_rhs = False def process_rhs(self, qn, connection): - rhs, params = super(EndsWith, self).process_rhs(qn, connection) + rhs, params = super().process_rhs(qn, connection) if params and not self.bilateral_transforms: params[0] = "%%%s" % connection.ops.prep_for_like_query(params[0]) return rhs, params @@ -479,7 +478,7 @@ class IEndsWith(PatternLookup): prepare_rhs = False def process_rhs(self, qn, connection): - rhs, params = super(IEndsWith, self).process_rhs(qn, connection) + rhs, params = super().process_rhs(qn, connection) if params and not self.bilateral_transforms: params[0] = "%%%s" % connection.ops.prep_for_like_query(params[0]) return rhs, params @@ -513,7 +512,7 @@ class Regex(BuiltinLookup): def as_sql(self, compiler, connection): if self.lookup_name in connection.operators: - return super(Regex, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) else: lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) @@ -571,7 +570,7 @@ class YearExact(YearLookup, Exact): except (IndexError, TypeError, ValueError): # Can't determine the bounds before executing the query, so skip # optimizations by falling back to a standard exact comparison. - return super(Exact, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) bounds = self.year_lookup_bounds(connection, rhs_params[0]) params.extend(bounds) return '%s BETWEEN %%s AND %%s' % lhs_sql, params diff --git a/django/db/models/manager.py b/django/db/models/manager.py index 2680f69986..dd97272d38 100644 --- a/django/db/models/manager.py +++ b/django/db/models/manager.py @@ -19,12 +19,12 @@ class BaseManager: def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial - obj = super(BaseManager, cls).__new__(cls) + obj = super().__new__(cls) obj._constructor_args = (args, kwargs) return obj def __init__(self): - super(BaseManager, self).__init__() + super().__init__() self._set_creation_counter() self.model = None self.name = None @@ -196,8 +196,8 @@ class ManagerDescriptor: class EmptyManager(Manager): def __init__(self, model): - super(EmptyManager, self).__init__() + super().__init__() self.model = model def get_queryset(self): - return super(EmptyManager, self).get_queryset().none() + return super().get_queryset().none() diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py index c94a03f549..7b1c46f15c 100644 --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -56,7 +56,7 @@ class Q(tree.Node): default = AND def __init__(self, *args, **kwargs): - super(Q, self).__init__(children=list(args) + list(kwargs.items())) + super().__init__(children=list(args) + list(kwargs.items())) def _combine(self, other, conn): if not isinstance(other, Q): diff --git a/django/db/models/signals.py b/django/db/models/signals.py index a511024342..dafd49fd05 100644 --- a/django/db/models/signals.py +++ b/django/db/models/signals.py @@ -25,13 +25,13 @@ class ModelSignal(Signal): def connect(self, receiver, sender=None, weak=True, dispatch_uid=None, apps=None): self._lazy_method( - super(ModelSignal, self).connect, apps, receiver, sender, + super().connect, apps, receiver, sender, weak=weak, dispatch_uid=dispatch_uid, ) def disconnect(self, receiver=None, sender=None, dispatch_uid=None, apps=None): return self._lazy_method( - super(ModelSignal, self).disconnect, apps, receiver, sender, dispatch_uid=dispatch_uid + super().disconnect, apps, receiver, sender, dispatch_uid=dispatch_uid ) diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 560ea2ef6d..76a595d2b1 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -928,7 +928,7 @@ class SQLInsertCompiler(SQLCompiler): def __init__(self, *args, **kwargs): self.return_id = False - super(SQLInsertCompiler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def field_as_sql(self, field, val): """ @@ -1181,7 +1181,7 @@ class SQLUpdateCompiler(SQLCompiler): non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ - cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) + cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None @@ -1217,7 +1217,7 @@ class SQLUpdateCompiler(SQLCompiler): query._extra = {} query.select = [] query.add_fields([query.get_meta().pk.name]) - super(SQLUpdateCompiler, self).pre_sql_setup() + super().pre_sql_setup() must_pre_select = count > 1 and not self.connection.features.update_can_self_select diff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py index cfdadefdff..03a5155b9b 100644 --- a/django/db/models/sql/subqueries.py +++ b/django/db/models/sql/subqueries.py @@ -88,7 +88,7 @@ class UpdateQuery(Query): compiler = 'SQLUpdateCompiler' def __init__(self, *args, **kwargs): - super(UpdateQuery, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._setup_query() def _setup_query(self): @@ -103,7 +103,7 @@ class UpdateQuery(Query): self.related_updates = {} def clone(self, klass=None, **kwargs): - return super(UpdateQuery, self).clone(klass, related_updates=self.related_updates.copy(), **kwargs) + return super().clone(klass, related_updates=self.related_updates.copy(), **kwargs) def update_batch(self, pk_list, values, using): self.add_update_values(values) @@ -176,7 +176,7 @@ class InsertQuery(Query): compiler = 'SQLInsertCompiler' def __init__(self, *args, **kwargs): - super(InsertQuery, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields = [] self.objs = [] diff --git a/django/forms/fields.py b/django/forms/fields.py index a3bdcd1713..e0c4edad52 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -121,7 +121,7 @@ class Field: self.validators = list(itertools.chain(self.default_validators, validators)) - super(Field, self).__init__() + super().__init__() def prepare_value(self, value): return value @@ -222,7 +222,7 @@ class CharField(Field): self.min_length = min_length self.strip = strip self.empty_value = empty_value - super(CharField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if min_length is not None: self.validators.append(validators.MinLengthValidator(int(min_length))) if max_length is not None: @@ -238,7 +238,7 @@ class CharField(Field): return value def widget_attrs(self, widget): - attrs = super(CharField, self).widget_attrs(widget) + attrs = super().widget_attrs(widget) if self.max_length is not None and not widget.is_hidden: # The HTML attribute is maxlength, not max_length. attrs['maxlength'] = str(self.max_length) @@ -259,8 +259,8 @@ class IntegerField(Field): self.max_value, self.min_value = max_value, min_value if kwargs.get('localize') and self.widget == NumberInput: # Localized number input is not well supported on most browsers - kwargs.setdefault('widget', super(IntegerField, self).widget) - super(IntegerField, self).__init__(*args, **kwargs) + kwargs.setdefault('widget', super().widget) + super().__init__(*args, **kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) @@ -272,7 +272,7 @@ class IntegerField(Field): Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ - value = super(IntegerField, self).to_python(value) + value = super().to_python(value) if value in self.empty_values: return None if self.localize: @@ -285,7 +285,7 @@ class IntegerField(Field): return value def widget_attrs(self, widget): - attrs = super(IntegerField, self).widget_attrs(widget) + attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput): if self.min_value is not None: attrs['min'] = self.min_value @@ -316,7 +316,7 @@ class FloatField(IntegerField): return value def validate(self, value): - super(FloatField, self).validate(value) + super().validate(value) # Check for NaN (which is the only thing not equal to itself) and +/- infinity if value != value or value in (Decimal('Inf'), Decimal('-Inf')): @@ -325,7 +325,7 @@ class FloatField(IntegerField): return value def widget_attrs(self, widget): - attrs = super(FloatField, self).widget_attrs(widget) + attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and 'step' not in widget.attrs: attrs.setdefault('step', 'any') return attrs @@ -338,7 +338,7 @@ class DecimalField(IntegerField): def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places - super(DecimalField, self).__init__(max_value, min_value, *args, **kwargs) + super().__init__(max_value, min_value, *args, **kwargs) self.validators.append(validators.DecimalValidator(max_digits, decimal_places)) def to_python(self, value): @@ -360,7 +360,7 @@ class DecimalField(IntegerField): return value def validate(self, value): - super(DecimalField, self).validate(value) + super().validate(value) if value in self.empty_values: return # Check for NaN, Inf and -Inf values. We can't compare directly for NaN, @@ -370,7 +370,7 @@ class DecimalField(IntegerField): raise ValidationError(self.error_messages['invalid'], code='invalid') def widget_attrs(self, widget): - attrs = super(DecimalField, self).widget_attrs(widget) + attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and 'step' not in widget.attrs: if self.decimal_places is not None: # Use exponential notation for small values since they might @@ -385,7 +385,7 @@ class DecimalField(IntegerField): class BaseTemporalField(Field): def __init__(self, input_formats=None, *args, **kwargs): - super(BaseTemporalField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if input_formats is not None: self.input_formats = input_formats @@ -425,7 +425,7 @@ class DateField(BaseTemporalField): return value.date() if isinstance(value, datetime.date): return value - return super(DateField, self).to_python(value) + return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).date() @@ -447,7 +447,7 @@ class TimeField(BaseTemporalField): return None if isinstance(value, datetime.time): return value - return super(TimeField, self).to_python(value) + return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).time() @@ -477,7 +477,7 @@ class DateTimeField(BaseTemporalField): if isinstance(value, datetime.date): result = datetime.datetime(value.year, value.month, value.day) return from_current_timezone(result) - result = super(DateTimeField, self).to_python(value) + result = super().to_python(value) return from_current_timezone(result) def strptime(self, value, format): @@ -513,7 +513,7 @@ class RegexField(CharField): 'Enter a valid value' is too generic for you. """ kwargs.setdefault('strip', False) - super(RegexField, self).__init__(max_length, min_length, *args, **kwargs) + super().__init__(max_length, min_length, *args, **kwargs) self._set_regex(regex) def _get_regex(self): @@ -536,7 +536,7 @@ class EmailField(CharField): default_validators = [validators.validate_email] def __init__(self, *args, **kwargs): - super(EmailField, self).__init__(*args, strip=True, **kwargs) + super().__init__(*args, strip=True, **kwargs) class FileField(Field): @@ -555,7 +555,7 @@ class FileField(Field): def __init__(self, *args, **kwargs): self.max_length = kwargs.pop('max_length', None) self.allow_empty_file = kwargs.pop('allow_empty_file', False) - super(FileField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def to_python(self, data): if data in self.empty_values: @@ -595,7 +595,7 @@ class FileField(Field): data = None if not data and initial: return initial - return super(FileField, self).clean(data) + return super().clean(data) def bound_data(self, data, initial): if data in (None, FILE_INPUT_CONTRADICTION): @@ -621,7 +621,7 @@ class ImageField(FileField): Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports). """ - f = super(ImageField, self).to_python(data) + f = super().to_python(data) if f is None: return None @@ -668,7 +668,7 @@ class URLField(CharField): default_validators = [validators.URLValidator()] def __init__(self, *args, **kwargs): - super(URLField, self).__init__(*args, strip=True, **kwargs) + super().__init__(*args, strip=True, **kwargs) def to_python(self, value): @@ -684,7 +684,7 @@ class URLField(CharField): # misformatted URLs. raise ValidationError(self.error_messages['invalid'], code='invalid') - value = super(URLField, self).to_python(value) + value = super().to_python(value) if value: url_fields = split_url(value) if not url_fields[0]: @@ -715,7 +715,7 @@ class BooleanField(Field): value = False else: value = bool(value) - return super(BooleanField, self).to_python(value) + return super().to_python(value) def validate(self, value): if not value and self.required: @@ -771,14 +771,14 @@ class ChoiceField(Field): def __init__(self, choices=(), required=True, widget=None, label=None, initial=None, help_text='', *args, **kwargs): - super(ChoiceField, self).__init__( + super().__init__( required=required, widget=widget, label=label, initial=initial, help_text=help_text, *args, **kwargs ) self.choices = choices def __deepcopy__(self, memo): - result = super(ChoiceField, self).__deepcopy__(memo) + result = super().__deepcopy__(memo) result._choices = copy.deepcopy(self._choices, memo) return result @@ -808,7 +808,7 @@ class ChoiceField(Field): """ Validates that the input is in self.choices. """ - super(ChoiceField, self).validate(value) + super().validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages['invalid_choice'], @@ -835,7 +835,7 @@ class TypedChoiceField(ChoiceField): def __init__(self, *args, **kwargs): self.coerce = kwargs.pop('coerce', lambda val: val) self.empty_value = kwargs.pop('empty_value', '') - super(TypedChoiceField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def _coerce(self, value): """ @@ -854,7 +854,7 @@ class TypedChoiceField(ChoiceField): return value def clean(self, value): - value = super(TypedChoiceField, self).clean(value) + value = super().clean(value) return self._coerce(value) @@ -904,7 +904,7 @@ class TypedMultipleChoiceField(MultipleChoiceField): def __init__(self, *args, **kwargs): self.coerce = kwargs.pop('coerce', lambda val: val) self.empty_value = kwargs.pop('empty_value', []) - super(TypedMultipleChoiceField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def _coerce(self, value): """ @@ -926,12 +926,12 @@ class TypedMultipleChoiceField(MultipleChoiceField): return new_value def clean(self, value): - value = super(TypedMultipleChoiceField, self).clean(value) + value = super().clean(value) return self._coerce(value) def validate(self, value): if value != self.empty_value: - super(TypedMultipleChoiceField, self).validate(value) + super().validate(value) elif self.required: raise ValidationError(self.error_messages['required'], code='required') @@ -941,7 +941,7 @@ class ComboField(Field): A Field whose clean() method calls multiple Field clean() methods. """ def __init__(self, fields=(), *args, **kwargs): - super(ComboField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Set 'required' to False on the individual fields, because the # required validation will be handled by ComboField, not by those # individual fields. @@ -954,7 +954,7 @@ class ComboField(Field): Validates the given value against all of self.fields, which is a list of Field instances. """ - super(ComboField, self).clean(value) + super().clean(value) for field in self.fields: value = field.clean(value) return value @@ -984,7 +984,7 @@ class MultiValueField(Field): def __init__(self, fields=(), *args, **kwargs): self.require_all_fields = kwargs.pop('require_all_fields', True) - super(MultiValueField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) for f in fields: f.error_messages.setdefault('incomplete', self.error_messages['incomplete']) @@ -996,7 +996,7 @@ class MultiValueField(Field): self.fields = fields def __deepcopy__(self, memo): - result = super(MultiValueField, self).__deepcopy__(memo) + result = super().__deepcopy__(memo) result.fields = tuple(x.__deepcopy__(memo) for x in self.fields) return result @@ -1088,7 +1088,7 @@ class FilePathField(ChoiceField): initial=None, help_text='', *args, **kwargs): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders - super(FilePathField, self).__init__( + super().__init__( choices=(), required=required, widget=widget, label=label, initial=initial, help_text=help_text, *args, **kwargs ) @@ -1152,7 +1152,7 @@ class SplitDateTimeField(MultiValueField): error_messages={'invalid': errors['invalid_time']}, localize=localize), ) - super(SplitDateTimeField, self).__init__(fields, *args, **kwargs) + super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: @@ -1171,7 +1171,7 @@ class GenericIPAddressField(CharField): def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.default_validators = validators.ip_address_validators(protocol, unpack_ipv4)[0] - super(GenericIPAddressField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def to_python(self, value): if value in self.empty_values: @@ -1189,7 +1189,7 @@ class SlugField(CharField): self.allow_unicode = kwargs.pop('allow_unicode', False) if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] - super(SlugField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) class UUIDField(CharField): @@ -1203,7 +1203,7 @@ class UUIDField(CharField): return value def to_python(self, value): - value = super(UUIDField, self).to_python(value) + value = super().to_python(value) if value in self.empty_values: return None if not isinstance(value, uuid.UUID): diff --git a/django/forms/formsets.py b/django/forms/formsets.py index 8a830916f9..4d8259c2c5 100644 --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -39,7 +39,7 @@ class ManagementForm(Form): # code. The POST value of them returned from the client is not checked. self.base_fields[MIN_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput) self.base_fields[MAX_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput) - super(ManagementForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) @html_safe diff --git a/django/forms/models.py b/django/forms/models.py index de1fb1e2bd..a95f281b45 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -289,7 +289,7 @@ class BaseModelForm(BaseForm): # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False - super(BaseModelForm, self).__init__( + super().__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, ) @@ -558,13 +558,13 @@ class BaseModelFormSet(BaseFormSet): self.initial_extra = kwargs.pop('initial', None) defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix} defaults.update(kwargs) - super(BaseModelFormSet, self).__init__(**defaults) + super().__init__(**defaults) def initial_form_count(self): """Returns the number of forms that are required in this FormSet.""" if not (self.data or self.files): return len(self.get_queryset()) - return super(BaseModelFormSet, self).initial_form_count() + return super().initial_form_count() def _existing_object(self, pk): if not hasattr(self, '_object_dict'): @@ -596,7 +596,7 @@ class BaseModelFormSet(BaseFormSet): kwargs['initial'] = self.initial_extra[i - self.initial_form_count()] except IndexError: pass - return super(BaseModelFormSet, self)._construct_form(i, **kwargs) + return super()._construct_form(i, **kwargs) def get_queryset(self): if not hasattr(self, '_queryset'): @@ -821,7 +821,7 @@ class BaseModelFormSet(BaseFormSet): else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget) - super(BaseModelFormSet, self).add_fields(form, index) + super().add_fields(form, index) def modelformset_factory(model, form=ModelForm, formfield_callback=None, @@ -871,8 +871,7 @@ class BaseInlineFormSet(BaseModelFormSet): else: qs = queryset.none() self.unique_fields = {self.fk.name} - super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, - queryset=qs, **kwargs) + super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs) # Add the generated field to form._meta.fields if it's defined to make # sure validation isn't skipped on that field. @@ -884,10 +883,10 @@ class BaseInlineFormSet(BaseModelFormSet): def initial_form_count(self): if self.save_as_new: return 0 - return super(BaseInlineFormSet, self).initial_form_count() + return super().initial_form_count() def _construct_form(self, i, **kwargs): - form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs) + form = super()._construct_form(i, **kwargs) if self.save_as_new: # Remove the primary key from the form's data, we are only # creating new instances @@ -926,7 +925,7 @@ class BaseInlineFormSet(BaseModelFormSet): return obj def add_fields(self, form, index): - super(BaseInlineFormSet, self).add_fields(form, index) + super().add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {'pk_field': True} @@ -954,7 +953,7 @@ class BaseInlineFormSet(BaseModelFormSet): def get_unique_error_message(self, unique_check): unique_check = [field for field in unique_check if field != self.fk.name] - return super(BaseInlineFormSet, self).get_unique_error_message(unique_check) + return super().get_unique_error_message(unique_check) def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): @@ -1076,7 +1075,7 @@ class InlineForeignKeyField(Field): else: kwargs["initial"] = self.parent_instance.pk kwargs["required"] = False - super(InlineForeignKeyField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean(self, value): if value in self.empty_values: @@ -1205,7 +1204,7 @@ class ModelChoiceField(ChoiceField): return value.serializable_value(self.to_field_name) else: return value.pk - return super(ModelChoiceField, self).prepare_value(value) + return super().prepare_value(value) def to_python(self, value): if value in self.empty_values: @@ -1239,7 +1238,7 @@ class ModelMultipleChoiceField(ModelChoiceField): def __init__(self, queryset, required=True, widget=None, label=None, initial=None, help_text='', *args, **kwargs): - super(ModelMultipleChoiceField, self).__init__( + super().__init__( queryset, None, required, widget, label, initial, help_text, *args, **kwargs ) @@ -1305,7 +1304,7 @@ class ModelMultipleChoiceField(ModelChoiceField): not isinstance(value, str) and not hasattr(value, '_meta')): return [super(ModelMultipleChoiceField, self).prepare_value(v) for v in value] - return super(ModelMultipleChoiceField, self).prepare_value(value) + return super().prepare_value(value) def has_changed(self, initial, data): if initial is None: diff --git a/django/forms/utils.py b/django/forms/utils.py index b199803ccc..bda4694e4f 100644 --- a/django/forms/utils.py +++ b/django/forms/utils.py @@ -80,7 +80,7 @@ class ErrorList(UserList, list): A collection of errors that knows how to display itself in various formats. """ def __init__(self, initlist=None, error_class=None): - super(ErrorList, self).__init__(initlist) + super().__init__(initlist) if error_class is None: self.error_class = 'errorlist' diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 71169d9618..4317a0fc39 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -255,10 +255,10 @@ class Input(Widget): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop('type', self.input_type) - super(Input, self).__init__(attrs) + super().__init__(attrs) def get_context(self, name, value, attrs=None): - context = super(Input, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) context['widget']['type'] = self.input_type return context @@ -288,13 +288,13 @@ class PasswordInput(Input): template_name = 'django/forms/widgets/password.html' def __init__(self, attrs=None, render_value=False): - super(PasswordInput, self).__init__(attrs) + super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None - return super(PasswordInput, self).get_context(name, value, attrs) + return super().get_context(name, value, attrs) class HiddenInput(Input): @@ -310,7 +310,7 @@ class MultipleHiddenInput(HiddenInput): template_name = 'django/forms/widgets/multiple_hidden.html' def get_context(self, name, value, attrs=None): - context = super(MultipleHiddenInput, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) final_attrs = context['widget']['attrs'] id_ = context['widget']['attrs'].get('id') @@ -392,7 +392,7 @@ class ClearableFileInput(FileInput): return value def get_context(self, name, value, attrs=None): - context = super(ClearableFileInput, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context.update({ @@ -406,7 +406,7 @@ class ClearableFileInput(FileInput): return context def value_from_datadict(self, data, files, name): - upload = super(ClearableFileInput, self).value_from_datadict(data, files, name) + upload = super().value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): @@ -420,7 +420,7 @@ class ClearableFileInput(FileInput): return upload def use_required_attribute(self, initial): - return super(ClearableFileInput, self).use_required_attribute(initial) and not initial + return super().use_required_attribute(initial) and not initial class Textarea(Widget): @@ -431,7 +431,7 @@ class Textarea(Widget): default_attrs = {'cols': '40', 'rows': '10'} if attrs: default_attrs.update(attrs) - super(Textarea, self).__init__(default_attrs) + super().__init__(default_attrs) class DateTimeBaseInput(TextInput): @@ -439,7 +439,7 @@ class DateTimeBaseInput(TextInput): supports_microseconds = False def __init__(self, attrs=None, format=None): - super(DateTimeBaseInput, self).__init__(attrs) + super().__init__(attrs) self.format = format if format else None def format_value(self, value): @@ -471,7 +471,7 @@ class CheckboxInput(Input): template_name = 'django/forms/widgets/checkbox.html' def __init__(self, attrs=None, check_test=None): - super(CheckboxInput, self).__init__(attrs) + super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test @@ -487,7 +487,7 @@ class CheckboxInput(Input): if attrs is None: attrs = {} attrs['checked'] = True - return super(CheckboxInput, self).get_context(name, value, attrs) + return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: @@ -517,7 +517,7 @@ class ChoiceWidget(Widget): option_inherits_attrs = True def __init__(self, attrs=None, choices=()): - super(ChoiceWidget, self).__init__(attrs) + super().__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. @@ -605,7 +605,7 @@ class ChoiceWidget(Widget): } def get_context(self, name, value, attrs=None): - context = super(ChoiceWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs) context['wrap_label'] = True return context @@ -657,7 +657,7 @@ class Select(ChoiceWidget): option_inherits_attrs = False def get_context(self, name, value, attrs=None): - context = super(Select, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context['widget']['attrs']['multiple'] = 'multiple' return context @@ -673,7 +673,7 @@ class Select(ChoiceWidget): Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ - use_required_attribute = super(Select, self).use_required_attribute(initial) + use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute @@ -692,7 +692,7 @@ class NullBooleanSelect(Select): ('2', ugettext_lazy('Yes')), ('3', ugettext_lazy('No')), ) - super(NullBooleanSelect, self).__init__(attrs, choices) + super().__init__(attrs, choices) def format_value(self, value): try: @@ -752,7 +752,7 @@ class CheckboxSelectMultiple(ChoiceWidget): """ if index is None: return '' - return super(CheckboxSelectMultiple, self).id_for_label(id_, index) + return super().id_for_label(id_, index) class MultiWidget(Widget): @@ -769,14 +769,14 @@ class MultiWidget(Widget): def __init__(self, widgets, attrs=None): self.widgets = [w() if isinstance(w, type) else w for w in widgets] - super(MultiWidget, self).__init__(attrs) + super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs=None): - context = super(MultiWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized @@ -837,7 +837,7 @@ class MultiWidget(Widget): media = property(_get_media) def __deepcopy__(self, memo): - obj = super(MultiWidget, self).__deepcopy__(memo) + obj = super().__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj @@ -858,7 +858,7 @@ class SplitDateTimeWidget(MultiWidget): DateInput(attrs=attrs, format=date_format), TimeInput(attrs=attrs, format=time_format), ) - super(SplitDateTimeWidget, self).__init__(widgets, attrs) + super().__init__(widgets, attrs) def decompress(self, value): if value: @@ -874,7 +874,7 @@ class SplitHiddenDateTimeWidget(SplitDateTimeWidget): template_name = 'django/forms/widgets/splithiddendatetime.html' def __init__(self, attrs=None, date_format=None, time_format=None): - super(SplitHiddenDateTimeWidget, self).__init__(attrs, date_format, time_format) + super().__init__(attrs, date_format, time_format) for widget in self.widgets: widget.input_type = 'hidden' @@ -928,7 +928,7 @@ class SelectDateWidget(Widget): self.day_none_value = self.none_value def get_context(self, name, value, attrs=None): - context = super(SelectDateWidget, self).get_context(name, value, attrs) + context = super().get_context(name, value, attrs) date_context = {} year_choices = [(i, i) for i in self.years] if self.is_required is False: diff --git a/django/http/cookie.py b/django/http/cookie.py index 36945ce106..52dff786c4 100644 --- a/django/http/cookie.py +++ b/django/http/cookie.py @@ -14,7 +14,7 @@ else: # allow assignment of constructed Morsels (e.g. for pickling) dict.__setitem__(self, key, value) else: - super(SimpleCookie, self).__setitem__(key, value) + super().__setitem__(key, value) def parse_cookie(cookie): diff --git a/django/http/request.py b/django/http/request.py index bae0b6f3ec..c91a51b48d 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -363,7 +363,7 @@ class QueryDict(MultiValueDict): _encoding = None def __init__(self, query_string=None, mutable=False, encoding=None): - super(QueryDict, self).__init__() + super().__init__() if not encoding: encoding = settings.DEFAULT_CHARSET self.encoding = encoding @@ -415,11 +415,11 @@ class QueryDict(MultiValueDict): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) - super(QueryDict, self).__setitem__(key, value) + super().__setitem__(key, value) def __delitem__(self, key): self._assert_mutable() - super(QueryDict, self).__delitem__(key) + super().__delitem__(key) def __copy__(self): result = self.__class__('', mutable=True, encoding=self.encoding) @@ -438,35 +438,35 @@ class QueryDict(MultiValueDict): self._assert_mutable() key = bytes_to_text(key, self.encoding) list_ = [bytes_to_text(elt, self.encoding) for elt in list_] - super(QueryDict, self).setlist(key, list_) + super().setlist(key, list_) def setlistdefault(self, key, default_list=None): self._assert_mutable() - return super(QueryDict, self).setlistdefault(key, default_list) + return super().setlistdefault(key, default_list) def appendlist(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) - super(QueryDict, self).appendlist(key, value) + super().appendlist(key, value) def pop(self, key, *args): self._assert_mutable() - return super(QueryDict, self).pop(key, *args) + return super().pop(key, *args) def popitem(self): self._assert_mutable() - return super(QueryDict, self).popitem() + return super().popitem() def clear(self): self._assert_mutable() - super(QueryDict, self).clear() + super().clear() def setdefault(self, key, default=None): self._assert_mutable() key = bytes_to_text(key, self.encoding) default = bytes_to_text(default, self.encoding) - return super(QueryDict, self).setdefault(key, default) + return super().setdefault(key, default) def copy(self): """Returns a mutable copy of this object.""" diff --git a/django/http/response.py b/django/http/response.py index 9c697f5b88..244883a3aa 100644 --- a/django/http/response.py +++ b/django/http/response.py @@ -280,7 +280,7 @@ class HttpResponse(HttpResponseBase): streaming = False def __init__(self, content=b'', *args, **kwargs): - super(HttpResponse, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content @@ -348,7 +348,7 @@ class StreamingHttpResponse(HttpResponseBase): streaming = True def __init__(self, streaming_content=(), *args, **kwargs): - super(StreamingHttpResponse, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # `streaming_content` should be an iterable of bytestrings. # See the `streaming_content` property methods. self.streaming_content = streaming_content @@ -396,14 +396,14 @@ class FileResponse(StreamingHttpResponse): value = iter(lambda: filelike.read(self.block_size), b'') else: self.file_to_stream = None - super(FileResponse, self)._set_streaming_content(value) + super()._set_streaming_content(value) class HttpResponseRedirectBase(HttpResponse): allowed_schemes = ['http', 'https', 'ftp'] def __init__(self, redirect_to, *args, **kwargs): - super(HttpResponseRedirectBase, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self['Location'] = iri_to_uri(redirect_to) parsed = urlparse(force_text(redirect_to)) if parsed.scheme and parsed.scheme not in self.allowed_schemes: @@ -432,7 +432,7 @@ class HttpResponseNotModified(HttpResponse): status_code = 304 def __init__(self, *args, **kwargs): - super(HttpResponseNotModified, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) del self['content-type'] @HttpResponse.content.setter @@ -458,7 +458,7 @@ class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, permitted_methods, *args, **kwargs): - super(HttpResponseNotAllowed, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self['Allow'] = ', '.join(permitted_methods) def __repr__(self): @@ -507,4 +507,4 @@ class JsonResponse(HttpResponse): json_dumps_params = {} kwargs.setdefault('content_type', 'application/json') data = json.dumps(data, cls=encoder, **json_dumps_params) - super(JsonResponse, self).__init__(content=data, **kwargs) + super().__init__(content=data, **kwargs) diff --git a/django/template/backends/django.py b/django/template/backends/django.py index eaa7c8fdc2..91bfbcf0bb 100644 --- a/django/template/backends/django.py +++ b/django/template/backends/django.py @@ -23,7 +23,7 @@ class DjangoTemplates(BaseEngine): options.setdefault('file_charset', settings.FILE_CHARSET) libraries = options.get('libraries', {}) options['libraries'] = self.get_templatetag_libraries(libraries) - super(DjangoTemplates, self).__init__(params) + super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): diff --git a/django/template/backends/dummy.py b/django/template/backends/dummy.py index 992465cd02..634ed32ffb 100644 --- a/django/template/backends/dummy.py +++ b/django/template/backends/dummy.py @@ -19,7 +19,7 @@ class TemplateStrings(BaseEngine): if options: raise ImproperlyConfigured( "Unknown options: {}".format(", ".join(options))) - super(TemplateStrings, self).__init__(params) + super().__init__(params) def from_string(self, template_code): return Template(template_code) diff --git a/django/template/backends/jinja2.py b/django/template/backends/jinja2.py index 3c5f7231bf..a055f76355 100644 --- a/django/template/backends/jinja2.py +++ b/django/template/backends/jinja2.py @@ -15,7 +15,7 @@ class Jinja2(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() - super(Jinja2, self).__init__(params) + super().__init__(params) self.context_processors = options.pop('context_processors', []) diff --git a/django/template/context.py b/django/template/context.py index dfc4ed69a6..551a89634c 100644 --- a/django/template/context.py +++ b/django/template/context.py @@ -12,7 +12,7 @@ class ContextPopException(Exception): class ContextDict(dict): def __init__(self, context, *args, **kwargs): - super(ContextDict, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) context.dicts.append(self) self.context = context @@ -35,7 +35,7 @@ class BaseContext: self.dicts.append(value) def __copy__(self): - duplicate = copy(super(BaseContext, self)) + duplicate = copy(super()) duplicate.dicts = self.dicts[:] return duplicate @@ -148,7 +148,7 @@ class Context(BaseContext): # Set to the original template -- as opposed to extended or included # templates -- during rendering, see bind_template. self.template = None - super(Context, self).__init__(dict_) + super().__init__(dict_) @contextmanager def bind_template(self, template): @@ -161,7 +161,7 @@ class Context(BaseContext): self.template = None def __copy__(self): - duplicate = super(Context, self).__copy__() + duplicate = super().__copy__() duplicate.render_context = copy(self.render_context) return duplicate @@ -224,8 +224,7 @@ class RequestContext(Context): using the "processors" keyword argument. """ def __init__(self, request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True): - super(RequestContext, self).__init__( - dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) + super().__init__(dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) self.request = request self._processors = () if processors is None else tuple(processors) self._processors_index = len(self.dicts) @@ -259,7 +258,7 @@ class RequestContext(Context): self.dicts[self._processors_index] = {} def new(self, values=None): - new_context = super(RequestContext, self).new(values) + new_context = super().new(values) # This is for backwards-compatibility: RequestContexts created via # Context.new don't include values from context processors. if hasattr(new_context, '_processors_index'): diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 888d837130..5f7efda912 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -894,7 +894,7 @@ class TemplateIfParser(IfParser): def __init__(self, parser, *args, **kwargs): self.template_parser = parser - super(TemplateIfParser, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def create_var(self, value): return TemplateLiteral(self.template_parser.compile_filter(value), value) diff --git a/django/template/exceptions.py b/django/template/exceptions.py index 08650fb97d..38980549f9 100644 --- a/django/template/exceptions.py +++ b/django/template/exceptions.py @@ -33,7 +33,7 @@ class TemplateDoesNotExist(Exception): if chain is None: chain = [] self.chain = chain - super(TemplateDoesNotExist, self).__init__(msg) + super().__init__(msg) class TemplateSyntaxError(Exception): diff --git a/django/template/library.py b/django/template/library.py index 0b66aad3e9..005255f484 100644 --- a/django/template/library.py +++ b/django/template/library.py @@ -184,7 +184,7 @@ class TagHelperNode(Node): class SimpleNode(TagHelperNode): def __init__(self, func, takes_context, args, kwargs, target_var): - super(SimpleNode, self).__init__(func, takes_context, args, kwargs) + super().__init__(func, takes_context, args, kwargs) self.target_var = target_var def render(self, context): @@ -201,7 +201,7 @@ class SimpleNode(TagHelperNode): class InclusionNode(TagHelperNode): def __init__(self, func, takes_context, args, kwargs, filename): - super(InclusionNode, self).__init__(func, takes_context, args, kwargs) + super().__init__(func, takes_context, args, kwargs) self.filename = filename def render(self, context): diff --git a/django/template/loader_tags.py b/django/template/loader_tags.py index b4f3f29be6..6a45b8c985 100644 --- a/django/template/loader_tags.py +++ b/django/template/loader_tags.py @@ -161,7 +161,7 @@ class IncludeNode(Node): self.template = template self.extra_context = kwargs.pop('extra_context', {}) self.isolated_context = kwargs.pop('isolated_context', False) - super(IncludeNode, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def render(self, context): """ diff --git a/django/template/loaders/cached.py b/django/template/loaders/cached.py index 1b9ee98c95..b86001a2f7 100644 --- a/django/template/loaders/cached.py +++ b/django/template/loaders/cached.py @@ -18,7 +18,7 @@ class Loader(BaseLoader): self.template_cache = {} self.get_template_cache = {} self.loaders = engine.get_template_loaders(loaders) - super(Loader, self).__init__(engine) + super().__init__(engine) def get_contents(self, origin): return origin.loader.get_contents(origin) @@ -52,7 +52,7 @@ class Loader(BaseLoader): return cached try: - template = super(Loader, self).get_template(template_name, skip) + template = super().get_template(template_name, skip) except TemplateDoesNotExist as e: self.get_template_cache[key] = copy_exception(e) if self.engine.debug else TemplateDoesNotExist raise diff --git a/django/template/loaders/filesystem.py b/django/template/loaders/filesystem.py index e3dda299b3..2e49e3d6b3 100644 --- a/django/template/loaders/filesystem.py +++ b/django/template/loaders/filesystem.py @@ -12,7 +12,7 @@ from .base import Loader as BaseLoader class Loader(BaseLoader): def __init__(self, engine, dirs=None): - super(Loader, self).__init__(engine) + super().__init__(engine) self.dirs = dirs def get_dirs(self): diff --git a/django/template/loaders/locmem.py b/django/template/loaders/locmem.py index 1b77c9805b..25d7672719 100644 --- a/django/template/loaders/locmem.py +++ b/django/template/loaders/locmem.py @@ -11,7 +11,7 @@ class Loader(BaseLoader): def __init__(self, engine, templates_dict): self.templates_dict = templates_dict - super(Loader, self).__init__(engine) + super().__init__(engine) def get_contents(self, origin): try: diff --git a/django/template/response.py b/django/template/response.py index e5c1fbfa66..4f98875966 100644 --- a/django/template/response.py +++ b/django/template/response.py @@ -33,7 +33,7 @@ class SimpleTemplateResponse(HttpResponse): # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. - super(SimpleTemplateResponse, self).__init__('', content_type, status, charset=charset) + super().__init__('', content_type, status, charset=charset) # _is_rendered tracks whether the template and context has been baked # into a final response. @@ -119,7 +119,7 @@ class SimpleTemplateResponse(HttpResponse): raise ContentNotRenderedError( 'The response content must be rendered before it can be iterated over.' ) - return super(SimpleTemplateResponse, self).__iter__() + return super().__iter__() @property def content(self): @@ -127,7 +127,7 @@ class SimpleTemplateResponse(HttpResponse): raise ContentNotRenderedError( 'The response content must be rendered before it can be accessed.' ) - return super(SimpleTemplateResponse, self).content + return super().content @content.setter def content(self, value): @@ -142,6 +142,5 @@ class TemplateResponse(SimpleTemplateResponse): def __init__(self, request, template, context=None, content_type=None, status=None, charset=None, using=None): - super(TemplateResponse, self).__init__( - template, context, content_type, status, charset, using) + super().__init__(template, context, content_type, status, charset, using) self._request = request diff --git a/django/test/client.py b/django/test/client.py index e793dac775..bdd045c82c 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -40,7 +40,7 @@ class RedirectCycleError(Exception): The test client has been asked to follow a redirect loop. """ def __init__(self, message, last_response): - super(RedirectCycleError, self).__init__(message) + super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain @@ -119,7 +119,7 @@ class ClientHandler(BaseHandler): """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks - super(ClientHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because @@ -430,7 +430,7 @@ class Client(RequestFactory): HTML rendered to the end-user. """ def __init__(self, enforce_csrf_checks=False, **defaults): - super(Client, self).__init__(**defaults) + super().__init__(**defaults) self.handler = ClientHandler(enforce_csrf_checks) self.exc_info = None @@ -527,8 +527,7 @@ class Client(RequestFactory): """ Requests a response from the server using GET. """ - response = super(Client, self).get(path, data=data, secure=secure, - **extra) + response = super().get(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -538,9 +537,7 @@ class Client(RequestFactory): """ Requests a response from the server using POST. """ - response = super(Client, self).post(path, data=data, - content_type=content_type, - secure=secure, **extra) + response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -549,8 +546,7 @@ class Client(RequestFactory): """ Request a response from the server using HEAD. """ - response = super(Client, self).head(path, data=data, secure=secure, - **extra) + response = super().head(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -560,9 +556,7 @@ class Client(RequestFactory): """ Request a response from the server using OPTIONS. """ - response = super(Client, self).options(path, data=data, - content_type=content_type, - secure=secure, **extra) + response = super().options(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -572,9 +566,7 @@ class Client(RequestFactory): """ Send a resource to the server using PUT. """ - response = super(Client, self).put(path, data=data, - content_type=content_type, - secure=secure, **extra) + response = super().put(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -584,9 +576,7 @@ class Client(RequestFactory): """ Send a resource to the server using PATCH. """ - response = super(Client, self).patch(path, data=data, - content_type=content_type, - secure=secure, **extra) + response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -596,9 +586,7 @@ class Client(RequestFactory): """ Send a DELETE request to the server. """ - response = super(Client, self).delete(path, data=data, - content_type=content_type, - secure=secure, **extra) + response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response @@ -607,7 +595,7 @@ class Client(RequestFactory): """ Send a TRACE request to the server. """ - response = super(Client, self).trace(path, data=data, secure=secure, **extra) + response = super().trace(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response diff --git a/django/test/html.py b/django/test/html.py index 319fd87a0f..900aa3d3f0 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -134,7 +134,7 @@ class Element: class RootElement(Element): def __init__(self): - super(RootElement, self).__init__(None, ()) + super().__init__(None, ()) def __str__(self): return ''.join(str(c) for c in self.children) diff --git a/django/test/runner.py b/django/test/runner.py index a0648b2f97..38578e7e0c 100644 --- a/django/test/runner.py +++ b/django/test/runner.py @@ -30,16 +30,16 @@ class DebugSQLTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger('django.db.backends') self.logger.setLevel(logging.DEBUG) - super(DebugSQLTextTestResult, self).__init__(stream, descriptions, verbosity) + super().__init__(stream, descriptions, verbosity) def startTest(self, test): self.debug_sql_stream = StringIO() self.handler = logging.StreamHandler(self.debug_sql_stream) self.logger.addHandler(self.handler) - super(DebugSQLTextTestResult, self).startTest(test) + super().startTest(test) def stopTest(self, test): - super(DebugSQLTextTestResult, self).stopTest(test) + super().stopTest(test) self.logger.removeHandler(self.handler) if self.showAll: self.debug_sql_stream.seek(0) @@ -47,12 +47,12 @@ class DebugSQLTextTestResult(unittest.TextTestResult): self.stream.writeln(self.separator2) def addError(self, test, err): - super(DebugSQLTextTestResult, self).addError(test, err) + super().addError(test, err) self.debug_sql_stream.seek(0) self.errors[-1] = self.errors[-1] + (self.debug_sql_stream.read(),) def addFailure(self, test, err): - super(DebugSQLTextTestResult, self).addFailure(test, err) + super().addFailure(test, err) self.debug_sql_stream.seek(0) self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),) @@ -333,7 +333,7 @@ class ParallelTestSuite(unittest.TestSuite): self.subsuites = partition_suite_by_case(suite) self.processes = processes self.failfast = failfast - super(ParallelTestSuite, self).__init__() + super().__init__() def run(self, result): """ diff --git a/django/test/selenium.py b/django/test/selenium.py index e1415339dd..2b14678b23 100644 --- a/django/test/selenium.py +++ b/django/test/selenium.py @@ -18,7 +18,7 @@ class SeleniumTestCaseBase(type(LiveServerTestCase)): Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome). """ - test_class = super(SeleniumTestCaseBase, cls).__new__(cls, name, bases, attrs) + test_class = super().__new__(cls, name, bases, attrs) # If the test class is either browser-specific or a test base, return it. if test_class.browser or not any(name.startswith('test') and callable(value) for name, value in attrs.items()): return test_class @@ -60,7 +60,7 @@ class SeleniumTestCase(LiveServerTestCase, metaclass=SeleniumTestCaseBase): def setUpClass(cls): cls.selenium = cls.create_webdriver() cls.selenium.implicitly_wait(cls.implicit_wait) - super(SeleniumTestCase, cls).setUpClass() + super().setUpClass() @classmethod def _tearDownClassInternal(cls): @@ -69,7 +69,7 @@ class SeleniumTestCase(LiveServerTestCase, metaclass=SeleniumTestCaseBase): # kept a connection alive. if hasattr(cls, 'selenium'): cls.selenium.quit() - super(SeleniumTestCase, cls)._tearDownClassInternal() + super()._tearDownClassInternal() @contextmanager def disable_implicit_wait(self): diff --git a/django/test/testcases.py b/django/test/testcases.py index 02398433d9..4c1d778795 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -66,10 +66,10 @@ class _AssertNumQueriesContext(CaptureQueriesContext): def __init__(self, test_case, num, connection): self.test_case = test_case self.num = num - super(_AssertNumQueriesContext, self).__init__(connection) + super().__init__(connection) def __exit__(self, exc_type, exc_value, traceback): - super(_AssertNumQueriesContext, self).__exit__(exc_type, exc_value, traceback) + super().__exit__(exc_type, exc_value, traceback) if exc_type is not None: return executed = len(self) @@ -157,7 +157,7 @@ class SimpleTestCase(unittest.TestCase): @classmethod def setUpClass(cls): - super(SimpleTestCase, cls).setUpClass() + super().setUpClass() if cls._overridden_settings: cls._cls_overridden_context = override_settings(**cls._overridden_settings) cls._cls_overridden_context.enable() @@ -183,7 +183,7 @@ class SimpleTestCase(unittest.TestCase): if hasattr(cls, '_cls_overridden_context'): cls._cls_overridden_context.disable() delattr(cls, '_cls_overridden_context') - super(SimpleTestCase, cls).tearDownClass() + super().tearDownClass() def __call__(self, result=None): """ @@ -203,7 +203,7 @@ class SimpleTestCase(unittest.TestCase): except Exception: result.addError(self, sys.exc_info()) return - super(SimpleTestCase, self).__call__(result) + super().__call__(result) if not skipped: try: self._post_teardown() @@ -799,7 +799,7 @@ class TransactionTestCase(SimpleTestCase): run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, installing these fixtures. """ - super(TransactionTestCase, self)._pre_setup() + super()._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.send( @@ -881,7 +881,7 @@ class TransactionTestCase(SimpleTestCase): """ try: self._fixture_teardown() - super(TransactionTestCase, self)._post_teardown() + super()._post_teardown() if self._should_reload_connections(): # Some DB cursors include SQL statements as part of cursor # creation. If you have a test that does a rollback, the effect @@ -980,7 +980,7 @@ class TestCase(TransactionTestCase): @classmethod def setUpClass(cls): - super(TestCase, cls).setUpClass() + super().setUpClass() if not connections_support_transactions(): return cls.cls_atomics = cls._enter_atomics() @@ -1008,7 +1008,7 @@ class TestCase(TransactionTestCase): cls._rollback_atomics(cls.cls_atomics) for conn in connections.all(): conn.close() - super(TestCase, cls).tearDownClass() + super().tearDownClass() @classmethod def setUpTestData(cls): @@ -1018,21 +1018,21 @@ class TestCase(TransactionTestCase): def _should_reload_connections(self): if connections_support_transactions(): return False - return super(TestCase, self)._should_reload_connections() + return super()._should_reload_connections() def _fixture_setup(self): if not connections_support_transactions(): # If the backend does not support transactions, we should reload # class data before each test self.setUpTestData() - return super(TestCase, self)._fixture_setup() + return super()._fixture_setup() assert not self.reset_sequences, 'reset_sequences cannot be used on TestCase instances' self.atomics = self._enter_atomics() def _fixture_teardown(self): if not connections_support_transactions(): - return super(TestCase, self)._fixture_teardown() + return super()._fixture_teardown() try: for db_name in reversed(self._databases_names()): if self._should_check_constraints(connections[db_name]): @@ -1141,7 +1141,7 @@ class FSFilesHandler(WSGIHandler): def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) - super(FSFilesHandler, self).__init__() + super().__init__() def _should_handle(self, path): """ @@ -1167,7 +1167,7 @@ class FSFilesHandler(WSGIHandler): return self.serve(request) except Http404: pass - return super(FSFilesHandler, self).get_response(request) + return super().get_response(request) def serve(self, request): os_rel_path = self.file_path(request.path) @@ -1181,7 +1181,7 @@ class FSFilesHandler(WSGIHandler): def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) - return super(FSFilesHandler, self).__call__(environ, start_response) + return super().__call__(environ, start_response) class _StaticFilesHandler(FSFilesHandler): @@ -1222,7 +1222,7 @@ class LiveServerThread(threading.Thread): self.error = None self.static_handler = static_handler self.connections_override = connections_override - super(LiveServerThread, self).__init__() + super().__init__() def run(self): """ @@ -1280,7 +1280,7 @@ class LiveServerTestCase(TransactionTestCase): @classmethod def setUpClass(cls): - super(LiveServerTestCase, cls).setUpClass() + super().setUpClass() connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to @@ -1331,7 +1331,7 @@ class LiveServerTestCase(TransactionTestCase): def tearDownClass(cls): cls._tearDownClassInternal() cls._live_server_modified_settings.disable() - super(LiveServerTestCase, cls).tearDownClass() + super().tearDownClass() class SerializeMixin: @@ -1354,9 +1354,9 @@ class SerializeMixin: "in the base class.".format(cls.__name__)) cls._lockfile = open(cls.lockfile) locks.lock(cls._lockfile, locks.LOCK_EX) - super(SerializeMixin, cls).setUpClass() + super().setUpClass() @classmethod def tearDownClass(cls): - super(SerializeMixin, cls).tearDownClass() + super().tearDownClass() cls._lockfile.close() diff --git a/django/test/utils.py b/django/test/utils.py index ef837ce5c7..43ce455762 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -65,7 +65,7 @@ class ContextList(list): return subcontext[key] raise KeyError(key) else: - return super(ContextList, self).__getitem__(key) + return super().__getitem__(key) def get(self, key, default=None): try: @@ -394,7 +394,7 @@ class override_settings(TestContextDecorator): """ def __init__(self, **kwargs): self.options = kwargs - super(override_settings, self).__init__() + super().__init__() def enable(self): # Keep this code at the beginning to leave the settings unchanged @@ -487,7 +487,7 @@ class modify_settings(override_settings): else: raise ValueError("Unsupported action: %s" % action) self.options[name] = value - super(modify_settings, self).enable() + super().enable() class override_system_checks(TestContextDecorator): @@ -501,7 +501,7 @@ class override_system_checks(TestContextDecorator): self.registry = registry self.new_checks = new_checks self.deployment_checks = deployment_checks - super(override_system_checks, self).__init__() + super().__init__() def enable(self): self.old_checks = self.registry.registered_checks @@ -654,7 +654,7 @@ class ignore_warnings(TestContextDecorator): self.filter_func = warnings.filterwarnings else: self.filter_func = warnings.simplefilter - super(ignore_warnings, self).__init__() + super().__init__() def enable(self): self.catch_warnings = warnings.catch_warnings() @@ -806,7 +806,7 @@ class override_script_prefix(TestContextDecorator): """ def __init__(self, prefix): self.prefix = prefix - super(override_script_prefix, self).__init__() + super().__init__() def enable(self): self.old_prefix = get_script_prefix() @@ -850,7 +850,7 @@ class isolate_apps(TestContextDecorator): def __init__(self, *installed_apps, **kwargs): self.installed_apps = installed_apps - super(isolate_apps, self).__init__(**kwargs) + super().__init__(**kwargs) def enable(self): self.old_apps = Options.default_apps diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py index 0dc6b89745..d838e19ceb 100644 --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -500,9 +500,7 @@ class LocaleRegexURLResolver(RegexURLResolver): self, urlconf_name, default_kwargs=None, app_name=None, namespace=None, prefix_default_language=True, ): - super(LocaleRegexURLResolver, self).__init__( - None, urlconf_name, default_kwargs, app_name, namespace, - ) + super().__init__(None, urlconf_name, default_kwargs, app_name, namespace) self.prefix_default_language = prefix_default_language @property diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index a61a445ab0..8e64328a2c 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -63,11 +63,10 @@ class MultiValueDict(dict): single name-value pairs. """ def __init__(self, key_to_list_mapping=()): - super(MultiValueDict, self).__init__(key_to_list_mapping) + super().__init__(key_to_list_mapping) def __repr__(self): - return "<%s: %s>" % (self.__class__.__name__, - super(MultiValueDict, self).__repr__()) + return "<%s: %s>" % (self.__class__.__name__, super().__repr__()) def __getitem__(self, key): """ @@ -75,7 +74,7 @@ class MultiValueDict(dict): raises KeyError if not found. """ try: - list_ = super(MultiValueDict, self).__getitem__(key) + list_ = super().__getitem__(key) except KeyError: raise MultiValueDictKeyError(repr(key)) try: @@ -84,7 +83,7 @@ class MultiValueDict(dict): return [] def __setitem__(self, key, value): - super(MultiValueDict, self).__setitem__(key, [value]) + super().__setitem__(key, [value]) def __copy__(self): return self.__class__([ @@ -134,7 +133,7 @@ class MultiValueDict(dict): return a new copy of values. """ try: - values = super(MultiValueDict, self).__getitem__(key) + values = super().__getitem__(key) except KeyError: if default is None: return [] @@ -152,7 +151,7 @@ class MultiValueDict(dict): return self._getlist(key, default, force_list=True) def setlist(self, key, list_): - super(MultiValueDict, self).__setitem__(key, list_) + super().__setitem__(key, list_) def setdefault(self, key, default=None): if key not in self: @@ -184,7 +183,7 @@ class MultiValueDict(dict): def lists(self): """Yields (key, list) pairs.""" - return iter(super(MultiValueDict, self).items()) + return iter(super().items()) def values(self): """Yield the last value on every key list.""" @@ -278,7 +277,7 @@ class DictWrapper(dict): quoted before being used. """ def __init__(self, data, func, prefix): - super(DictWrapper, self).__init__(data) + super().__init__(data) self.func = func self.prefix = prefix @@ -293,7 +292,7 @@ class DictWrapper(dict): key = key[len(self.prefix):] else: use_func = False - value = super(DictWrapper, self).__getitem__(key) + value = super().__getitem__(key) if use_func: return self.func(value) return value diff --git a/django/utils/decorators.py b/django/utils/decorators.py index 7621d2fabd..87a20cf23b 100644 --- a/django/utils/decorators.py +++ b/django/utils/decorators.py @@ -9,7 +9,7 @@ class classonlymethod(classmethod): def __get__(self, instance, cls=None): if instance is not None: raise AttributeError("This method is available only on the class, not on instances.") - return super(classonlymethod, self).__get__(instance, cls) + return super().__get__(instance, cls) def method_decorator(decorator, name=''): diff --git a/django/utils/deprecation.py b/django/utils/deprecation.py index 2ef95bc343..cb8b001583 100644 --- a/django/utils/deprecation.py +++ b/django/utils/deprecation.py @@ -45,7 +45,7 @@ class RenameMethodsBase(type): renamed_methods = () def __new__(cls, name, bases, attrs): - new_class = super(RenameMethodsBase, cls).__new__(cls, name, bases, attrs) + new_class = super().__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ @@ -79,13 +79,13 @@ class DeprecationInstanceCheck(type): "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative), self.deprecation_warning, 2 ) - return super(DeprecationInstanceCheck, self).__instancecheck__(instance) + return super().__instancecheck__(instance) class MiddlewareMixin: def __init__(self, get_response=None): self.get_response = get_response - super(MiddlewareMixin, self).__init__() + super().__init__() def __call__(self, request): response = None diff --git a/django/utils/functional.py b/django/utils/functional.py index 30e484eaa3..6b4126764c 100644 --- a/django/utils/functional.py +++ b/django/utils/functional.py @@ -348,7 +348,7 @@ class SimpleLazyObject(LazyObject): value. """ self.__dict__['_setupfunc'] = func - super(SimpleLazyObject, self).__init__() + super().__init__() def _setup(self): self._wrapped = self._setupfunc() diff --git a/django/utils/jslex.py b/django/utils/jslex.py index 98b5d56e9d..7738ce468a 100644 --- a/django/utils/jslex.py +++ b/django/utils/jslex.py @@ -179,7 +179,7 @@ class JsLexer(Lexer): } def __init__(self): - super(JsLexer, self).__init__(self.states, 'reg') + super().__init__(self.states, 'reg') def prepare_js_for_gettext(js): diff --git a/django/utils/log.py b/django/utils/log.py index 77e2f59250..495b846a62 100644 --- a/django/utils/log.py +++ b/django/utils/log.py @@ -159,7 +159,7 @@ class RequireDebugTrue(logging.Filter): class ServerFormatter(logging.Formatter): def __init__(self, *args, **kwargs): self.style = color_style() - super(ServerFormatter, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def format(self, record): msg = record.msg @@ -187,7 +187,7 @@ class ServerFormatter(logging.Formatter): record.server_time = self.formatTime(record, self.datefmt) record.msg = msg - return super(ServerFormatter, self).format(record) + return super().format(record) def uses_server_time(self): return self._fmt.find('%(server_time)') >= 0 diff --git a/django/utils/safestring.py b/django/utils/safestring.py index 2dfbd01cfe..9b83a947d5 100644 --- a/django/utils/safestring.py +++ b/django/utils/safestring.py @@ -28,7 +28,7 @@ class SafeBytes(bytes, SafeData): Concatenating a safe byte string with another safe byte string or safe unicode string is safe. Otherwise, the result is no longer safe. """ - t = super(SafeBytes, self).__add__(rhs) + t = super().__add__(rhs) if isinstance(rhs, SafeText): return SafeText(t) elif isinstance(rhs, SafeBytes): @@ -61,7 +61,7 @@ class SafeText(str, SafeData): Concatenating a safe unicode string with another safe byte string or safe unicode string is safe. Otherwise, the result is no longer safe. """ - t = super(SafeText, self).__add__(rhs) + t = super().__add__(rhs) if isinstance(rhs, SafeData): return SafeText(t) return t diff --git a/django/utils/six.py b/django/utils/six.py index 95f16f58d9..975fbfcf4f 100644 --- a/django/utils/six.py +++ b/django/utils/six.py @@ -101,7 +101,7 @@ class _LazyDescr: class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): - super(MovedModule, self).__init__(name) + super().__init__(name) if PY3: if new is None: new = name @@ -122,7 +122,7 @@ class MovedModule(_LazyDescr): class _LazyModule(types.ModuleType): def __init__(self, name): - super(_LazyModule, self).__init__(name) + super().__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): @@ -137,7 +137,7 @@ class _LazyModule(types.ModuleType): class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): - super(MovedAttribute, self).__init__(name) + super().__init__(name) if PY3: if new_mod is None: new_mod = name diff --git a/django/utils/text.py b/django/utils/text.py index 26a8b859ef..70f6b60777 100644 --- a/django/utils/text.py +++ b/django/utils/text.py @@ -64,7 +64,7 @@ class Truncator(SimpleLazyObject): An object used to truncate text, either by characters or words. """ def __init__(self, text): - super(Truncator, self).__init__(lambda: force_text(text)) + super().__init__(lambda: force_text(text)) def add_truncation_text(self, text, truncate=None): if truncate is None: diff --git a/django/views/decorators/csrf.py b/django/views/decorators/csrf.py index d5ff6da90e..19e8fb30de 100644 --- a/django/views/decorators/csrf.py +++ b/django/views/decorators/csrf.py @@ -33,7 +33,7 @@ class _EnsureCsrfCookie(CsrfViewMiddleware): return None def process_view(self, request, callback, callback_args, callback_kwargs): - retval = super(_EnsureCsrfCookie, self).process_view(request, callback, callback_args, callback_kwargs) + retval = super().process_view(request, callback, callback_args, callback_kwargs) # Forces process_response to send the cookie get_token(request) return retval diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py index c738be8986..f0c50a42b3 100644 --- a/django/views/generic/dates.py +++ b/django/views/generic/dates.py @@ -668,7 +668,7 @@ class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailV lookup_kwargs = self._make_single_date_lookup(date) qs = qs.filter(**lookup_kwargs) - return super(BaseDetailView, self).get_object(queryset=qs) + return super().get_object(queryset=qs) class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView): diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py index b84585804b..24b406523d 100644 --- a/django/views/generic/detail.py +++ b/django/views/generic/detail.py @@ -102,7 +102,7 @@ class SingleObjectMixin(ContextMixin): if context_object_name: context[context_object_name] = self.object context.update(kwargs) - return super(SingleObjectMixin, self).get_context_data(**context) + return super().get_context_data(**context) class BaseDetailView(SingleObjectMixin, View): @@ -130,7 +130,7 @@ class SingleObjectTemplateResponseMixin(TemplateResponseMixin): * ``<app_label>/<model_name><template_name_suffix>.html`` """ try: - names = super(SingleObjectTemplateResponseMixin, self).get_template_names() + names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. diff --git a/django/views/generic/edit.py b/django/views/generic/edit.py index 258d624812..7d8a86b9fc 100644 --- a/django/views/generic/edit.py +++ b/django/views/generic/edit.py @@ -91,7 +91,7 @@ class FormMixin(ContextMixin): """ if 'form' not in kwargs: kwargs['form'] = self.get_form() - return super(FormMixin, self).get_context_data(**kwargs) + return super().get_context_data(**kwargs) class ModelFormMixin(FormMixin, SingleObjectMixin): @@ -135,7 +135,7 @@ class ModelFormMixin(FormMixin, SingleObjectMixin): """ Returns the keyword arguments for instantiating the form. """ - kwargs = super(ModelFormMixin, self).get_form_kwargs() + kwargs = super().get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) return kwargs @@ -160,7 +160,7 @@ class ModelFormMixin(FormMixin, SingleObjectMixin): If the form is valid, save the associated model. """ self.object = form.save() - return super(ModelFormMixin, self).form_valid(form) + return super().form_valid(form) class ProcessFormView(View): @@ -210,11 +210,11 @@ class BaseCreateView(ModelFormMixin, ProcessFormView): """ def get(self, request, *args, **kwargs): self.object = None - return super(BaseCreateView, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None - return super(BaseCreateView, self).post(request, *args, **kwargs) + return super().post(request, *args, **kwargs) class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView): @@ -233,11 +233,11 @@ class BaseUpdateView(ModelFormMixin, ProcessFormView): """ def get(self, request, *args, **kwargs): self.object = self.get_object() - return super(BaseUpdateView, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() - return super(BaseUpdateView, self).post(request, *args, **kwargs) + return super().post(request, *args, **kwargs) class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView): diff --git a/django/views/generic/list.py b/django/views/generic/list.py index e37f4f1ac0..39dc856e55 100644 --- a/django/views/generic/list.py +++ b/django/views/generic/list.py @@ -145,7 +145,7 @@ class MultipleObjectMixin(ContextMixin): if context_object_name is not None: context[context_object_name] = queryset context.update(kwargs) - return super(MultipleObjectMixin, self).get_context_data(**context) + return super().get_context_data(**context) class BaseListView(MultipleObjectMixin, View): @@ -184,7 +184,7 @@ class MultipleObjectTemplateResponseMixin(TemplateResponseMixin): a list. May not be called if render_to_response is overridden. """ try: - names = super(MultipleObjectTemplateResponseMixin, self).get_template_names() + names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. diff --git a/tests/admin_changelist/admin.py b/tests/admin_changelist/admin.py index 39494e99d3..915dc32ef0 100644 --- a/tests/admin_changelist/admin.py +++ b/tests/admin_changelist/admin.py @@ -12,7 +12,7 @@ site.register(User, UserAdmin) class CustomPaginator(Paginator): def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True): - super(CustomPaginator, self).__init__(queryset, 5, orphans=2, allow_empty_first_page=allow_empty_first_page) + super().__init__(queryset, 5, orphans=2, allow_empty_first_page=allow_empty_first_page) class EventAdmin(admin.ModelAdmin): @@ -39,7 +39,7 @@ class ChildAdmin(admin.ModelAdmin): list_filter = ['parent', 'age'] def get_queryset(self, request): - return super(ChildAdmin, self).get_queryset(request).select_related("parent") + return super().get_queryset(request).select_related("parent") class CustomPaginationAdmin(ChildAdmin): @@ -51,8 +51,7 @@ class FilteredChildAdmin(admin.ModelAdmin): list_per_page = 10 def get_queryset(self, request): - return super(FilteredChildAdmin, self).get_queryset(request).filter( - name__contains='filtered') + return super().get_queryset(request).filter(name__contains='filtered') class BandAdmin(admin.ModelAdmin): @@ -85,7 +84,7 @@ class DynamicListDisplayChildAdmin(admin.ModelAdmin): list_display = ('parent', 'name', 'age') def get_list_display(self, request): - my_list_display = super(DynamicListDisplayChildAdmin, self).get_list_display(request) + my_list_display = super().get_list_display(request) if request.user.username == 'noparents': my_list_display = list(my_list_display) my_list_display.remove('parent') @@ -124,7 +123,7 @@ class DynamicListFilterChildAdmin(admin.ModelAdmin): list_filter = ('parent', 'name', 'age') def get_list_filter(self, request): - my_list_filter = super(DynamicListFilterChildAdmin, self).get_list_filter(request) + my_list_filter = super().get_list_filter(request) if request.user.username == 'noparents': my_list_filter = list(my_list_filter) my_list_filter.remove('parent') @@ -135,7 +134,7 @@ class DynamicSearchFieldsChildAdmin(admin.ModelAdmin): search_fields = ('name',) def get_search_fields(self, request): - search_fields = super(DynamicSearchFieldsChildAdmin, self).get_search_fields(request) + search_fields = super().get_search_fields(request) search_fields += ('age',) return search_fields diff --git a/tests/admin_changelist/models.py b/tests/admin_changelist/models.py index 0abb061548..1cec7b8a82 100644 --- a/tests/admin_changelist/models.py +++ b/tests/admin_changelist/models.py @@ -94,7 +94,7 @@ class UnorderedObject(models.Model): class OrderedObjectManager(models.Manager): def get_queryset(self): - return super(OrderedObjectManager, self).get_queryset().order_by('number') + return super().get_queryset().order_by('number') class OrderedObject(models.Model): diff --git a/tests/admin_checks/tests.py b/tests/admin_checks/tests.py index e8714fe1a8..e081caeca1 100644 --- a/tests/admin_checks/tests.py +++ b/tests/admin_checks/tests.py @@ -106,7 +106,7 @@ class SystemChecksTestCase(SimpleTestCase): def test_allows_checks_relying_on_other_modeladmins(self): class MyBookAdmin(admin.ModelAdmin): def check(self, **kwargs): - errors = super(MyBookAdmin, self).check(**kwargs) + errors = super().check(**kwargs) author_admin = self.admin_site._registry.get(Author) if author_admin is None: errors.append('AuthorAdmin missing!') diff --git a/tests/admin_custom_urls/models.py b/tests/admin_custom_urls/models.py index 840d9b9f38..1fc30ec18c 100644 --- a/tests/admin_custom_urls/models.py +++ b/tests/admin_custom_urls/models.py @@ -28,7 +28,7 @@ class ActionAdmin(admin.ModelAdmin): Remove all entries named 'name' from the ModelAdmin instance URL patterns list """ - return [url for url in super(ActionAdmin, self).get_urls() if url.name != name] + return [url for url in super().get_urls() if url.name != name] def get_urls(self): # Add the URL of our custom 'add_view' view to the front of the URLs @@ -71,8 +71,10 @@ class Car(models.Model): class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): - return super(CarAdmin, self).response_add( - request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk])) + return super().response_add( + request, obj, + post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk]), + ) site = admin.AdminSite(name='admin_custom_urls') diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index 4dc6c3365a..3f2f33bf3c 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -168,12 +168,12 @@ class BookAdminWithCustomQueryset(ModelAdmin): def __init__(self, user, *args, **kwargs): self.user = user - super(BookAdminWithCustomQueryset, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) list_filter = ('year',) def get_queryset(self, request): - return super(BookAdminWithCustomQueryset, self).get_queryset(request).filter(author=self.user) + return super().get_queryset(request).filter(author=self.user) class BookAdminRelatedOnlyFilter(ModelAdmin): diff --git a/tests/admin_inlines/admin.py b/tests/admin_inlines/admin.py index c3bc8d7698..f9e50d1b91 100644 --- a/tests/admin_inlines/admin.py +++ b/tests/admin_inlines/admin.py @@ -193,7 +193,7 @@ class SomeChildModelForm(forms.ModelForm): } def __init__(self, *args, **kwargs): - super(SomeChildModelForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['name'].label = 'new label' diff --git a/tests/admin_inlines/models.py b/tests/admin_inlines/models.py index 31e692b60e..2c2601961e 100644 --- a/tests/admin_inlines/models.py +++ b/tests/admin_inlines/models.py @@ -53,7 +53,7 @@ class NonAutoPKBook(models.Model): test_pk = random.randint(1, 99999) if not NonAutoPKBook.objects.filter(rand_pk=test_pk).exists(): self.rand_pk = test_pk - super(NonAutoPKBook, self).save(*args, **kwargs) + super().save(*args, **kwargs) class EditablePKBook(models.Model): diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py index 77597d0fb5..0398616d2e 100644 --- a/tests/admin_ordering/tests.py +++ b/tests/admin_ordering/tests.py @@ -161,12 +161,12 @@ class TestRelatedFieldsAdminOrdering(TestCase): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'band': kwargs["queryset"] = Band.objects.filter(rank__gt=2) - return super(SongAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) + return super().formfield_for_foreignkey(db_field, request, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'other_interpreters': kwargs["queryset"] = Band.objects.filter(rank__gt=2) - return super(SongAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) + return super().formfield_for_foreignkey(db_field, request, **kwargs) class StaticOrderingBandAdmin(admin.ModelAdmin): ordering = ('rank',) diff --git a/tests/admin_scripts/management/commands/custom_startproject.py b/tests/admin_scripts/management/commands/custom_startproject.py index 3fa19d98cc..b258e4b80d 100644 --- a/tests/admin_scripts/management/commands/custom_startproject.py +++ b/tests/admin_scripts/management/commands/custom_startproject.py @@ -3,5 +3,5 @@ from django.core.management.commands.startproject import Command as BaseCommand class Command(BaseCommand): def add_arguments(self, parser): - super(Command, self).add_arguments(parser) + super().add_arguments(parser) parser.add_argument('--extra', help='An arbitrary extra value passed to the context') diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index 88a0260358..ad7d9ef742 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -38,7 +38,7 @@ class AdminScriptTestCase(unittest.TestCase): @classmethod def setUpClass(cls): - super(AdminScriptTestCase, cls).setUpClass() + super().setUpClass() cls.test_dir = os.path.realpath(os.path.join( tempfile.gettempdir(), cls.__name__, @@ -52,7 +52,7 @@ class AdminScriptTestCase(unittest.TestCase): @classmethod def tearDownClass(cls): shutil.rmtree(cls.test_dir) - super(AdminScriptTestCase, cls).tearDownClass() + super().tearDownClass() def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 3a5f750309..1827039266 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -107,11 +107,7 @@ class ArticleAdmin(admin.ModelAdmin): ) def changelist_view(self, request): - return super(ArticleAdmin, self).changelist_view( - request, extra_context={ - 'extra_var': 'Hello!' - } - ) + return super().changelist_view(request, extra_context={'extra_var': 'Hello!'}) def modeladmin_year(self, obj): return obj.date.year @@ -125,7 +121,7 @@ class ArticleAdmin(admin.ModelAdmin): 'from@example.com', ['to@example.com'] ).send() - return super(ArticleAdmin, self).delete_model(request, obj) + return super().delete_model(request, obj) def save_model(self, request, obj, form, change=True): EmailMessage( @@ -134,7 +130,7 @@ class ArticleAdmin(admin.ModelAdmin): 'from@example.com', ['to@example.com'] ).send() - return super(ArticleAdmin, self).save_model(request, obj, form, change) + return super().save_model(request, obj, form, change) class ArticleAdmin2(admin.ModelAdmin): @@ -162,11 +158,7 @@ class CustomArticleAdmin(admin.ModelAdmin): popup_response_template = 'custom_admin/popup_response.html' def changelist_view(self, request): - return super(CustomArticleAdmin, self).changelist_view( - request, extra_context={ - 'extra_var': 'Hello!' - } - ) + return super().changelist_view(request, extra_context={'extra_var': 'Hello!'}) class ThingAdmin(admin.ModelAdmin): @@ -207,12 +199,12 @@ class PersonAdmin(admin.ModelAdmin): save_as = True def get_changelist_formset(self, request, **kwargs): - return super(PersonAdmin, self).get_changelist_formset(request, formset=BasePersonModelFormSet, **kwargs) + return super().get_changelist_formset(request, formset=BasePersonModelFormSet, **kwargs) def get_queryset(self, request): # Order by a field that isn't in list display, to be able to test # whether ordering is preserved. - return super(PersonAdmin, self).get_queryset(request).order_by('age') + return super().get_queryset(request).order_by('age') class FooAccountAdmin(admin.StackedInline): @@ -312,7 +304,7 @@ class ParentAdmin(admin.ModelAdmin): list_editable = ('name',) def save_related(self, request, form, formsets, change): - super(ParentAdmin, self).save_related(request, form, formsets, change) + super().save_related(request, form, formsets, change) first_name, last_name = form.instance.name.split() for child in form.instance.child_set.all(): if len(child.name.split()) < 2: @@ -322,7 +314,7 @@ class ParentAdmin(admin.ModelAdmin): class EmptyModelAdmin(admin.ModelAdmin): def get_queryset(self, request): - return super(EmptyModelAdmin, self).get_queryset(request).filter(pk__gt=1) + return super().get_queryset(request).filter(pk__gt=1) class OldSubscriberAdmin(admin.ModelAdmin): @@ -521,7 +513,7 @@ class CoverLetterAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super(CoverLetterAdmin, self).get_queryset(request).defer('date_written') + return super().get_queryset(request).defer('date_written') class PaperAdmin(admin.ModelAdmin): @@ -533,7 +525,7 @@ class PaperAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super(PaperAdmin, self).get_queryset(request).only('title') + return super().get_queryset(request).only('title') class ShortMessageAdmin(admin.ModelAdmin): @@ -545,7 +537,7 @@ class ShortMessageAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super(ShortMessageAdmin, self).get_queryset(request).defer('timestamp') + return super().get_queryset(request).defer('timestamp') class TelegramAdmin(admin.ModelAdmin): @@ -557,7 +549,7 @@ class TelegramAdmin(admin.ModelAdmin): """ def get_queryset(self, request): - return super(TelegramAdmin, self).get_queryset(request).only('title') + return super().get_queryset(request).only('title') class StoryForm(forms.ModelForm): @@ -594,9 +586,7 @@ class PluggableSearchPersonAdmin(admin.ModelAdmin): search_fields = ('name',) def get_search_results(self, request, queryset, search_term): - queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results( - request, queryset, search_term - ) + queryset, use_distinct = super().get_search_results(request, queryset, search_term) try: search_term_as_int = int(search_term) except ValueError: @@ -713,13 +703,13 @@ class UnorderedObjectAdmin(admin.ModelAdmin): class UndeletableObjectAdmin(admin.ModelAdmin): def change_view(self, *args, **kwargs): kwargs['extra_context'] = {'show_delete': False} - return super(UndeletableObjectAdmin, self).change_view(*args, **kwargs) + return super().change_view(*args, **kwargs) class UnchangeableObjectAdmin(admin.ModelAdmin): def get_urls(self): # Disable change_view, but leave other urls untouched - urlpatterns = super(UnchangeableObjectAdmin, self).get_urls() + urlpatterns = super().get_urls() return [p for p in urlpatterns if p.name and not p.name.endswith("_change")] @@ -775,7 +765,7 @@ class DependentChildAdminForm(forms.ModelForm): if parent.family_name and parent.family_name != self.cleaned_data.get('family_name'): raise ValidationError("Children must share a family name with their parents " + "in this contrived test case") - return super(DependentChildAdminForm, self).clean() + return super().clean() class DependentChildInline(admin.TabularInline): @@ -883,18 +873,18 @@ class GetFormsetsArgumentCheckingAdmin(admin.ModelAdmin): def add_view(self, request, *args, **kwargs): request.is_add_view = True - return super(GetFormsetsArgumentCheckingAdmin, self).add_view(request, *args, **kwargs) + return super().add_view(request, *args, **kwargs) def change_view(self, request, *args, **kwargs): request.is_add_view = False - return super(GetFormsetsArgumentCheckingAdmin, self).change_view(request, *args, **kwargs) + return super().change_view(request, *args, **kwargs) def get_formsets_with_inlines(self, request, obj=None): if request.is_add_view and obj is not None: raise Exception("'obj' passed to get_formsets_with_inlines wasn't None during add_view") if not request.is_add_view and obj is None: raise Exception("'obj' passed to get_formsets_with_inlines was None during change_view") - return super(GetFormsetsArgumentCheckingAdmin, self).get_formsets_with_inlines(request, obj) + return super().get_formsets_with_inlines(request, obj) site = admin.AdminSite(name="admin") diff --git a/tests/admin_views/customadmin.py b/tests/admin_views/customadmin.py index 5eb1f2baa2..2fbbb78595 100644 --- a/tests/admin_views/customadmin.py +++ b/tests/admin_views/customadmin.py @@ -21,24 +21,24 @@ class Admin2(admin.AdminSite): # A custom index view. def index(self, request, extra_context=None): - return super(Admin2, self).index(request, {'foo': '*bar*'}) + return super().index(request, {'foo': '*bar*'}) def get_urls(self): return [ url(r'^my_view/$', self.admin_view(self.my_view), name='my_view'), - ] + super(Admin2, self).get_urls() + ] + super().get_urls() def my_view(self, request): return HttpResponse("Django is a magical pony!") def password_change(self, request, extra_context=None): - return super(Admin2, self).password_change(request, {'spam': 'eggs'}) + return super().password_change(request, {'spam': 'eggs'}) class UserLimitedAdmin(UserAdmin): # used for testing password change on a user not in queryset def get_queryset(self, request): - qs = super(UserLimitedAdmin, self).get_queryset(request) + qs = super().get_queryset(request) return qs.filter(is_superuser=False) diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py index 89373f6ed3..4364260ef7 100644 --- a/tests/admin_views/models.py +++ b/tests/admin_views/models.py @@ -805,7 +805,7 @@ class DependentChild(models.Model): class _Manager(models.Manager): def get_queryset(self): - return super(_Manager, self).get_queryset().filter(pk__gt=1) + return super().get_queryset().filter(pk__gt=1) class FilteredManager(models.Model): diff --git a/tests/admin_widgets/models.py b/tests/admin_widgets/models.py index fcc86ddeb8..422f8b0286 100644 --- a/tests/admin_widgets/models.py +++ b/tests/admin_widgets/models.py @@ -37,7 +37,7 @@ class Album(models.Model): class HiddenInventoryManager(models.Manager): def get_queryset(self): - return super(HiddenInventoryManager, self).get_queryset().filter(hidden=False) + return super().get_queryset().filter(hidden=False) class Inventory(models.Model): diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index b9462498cc..b0ec18968e 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -407,7 +407,7 @@ class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): - super(AdminFileWidgetTests, cls).setUpTestData() + super().setUpTestData() band = Band.objects.create(name='Linkin Park') cls.album = band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' @@ -854,7 +854,7 @@ class DateTimePickerAltTimezoneSeleniumTests(DateTimePickerShortcutsSeleniumTest class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): - super(HorizontalVerticalFilterSeleniumTests, self).setUp() + super().setUp() self.lisa = Student.objects.create(name='Lisa') self.john = Student.objects.create(name='John') self.bob = Student.objects.create(name='Bob') @@ -1171,7 +1171,7 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): - super(AdminRawIdWidgetSeleniumTests, self).setUp() + super().setUp() Band.objects.create(id=42, name='Bogey Blues') Band.objects.create(id=98, name='Green Potatoes') diff --git a/tests/admin_widgets/widgetadmin.py b/tests/admin_widgets/widgetadmin.py index a03e044b9d..a471a362fb 100644 --- a/tests/admin_widgets/widgetadmin.py +++ b/tests/admin_widgets/widgetadmin.py @@ -20,7 +20,7 @@ class CarTireAdmin(admin.ModelAdmin): if db_field.name == "car": kwargs["queryset"] = Car.objects.filter(owner=request.user) return db_field.formfield(**kwargs) - return super(CarTireAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) + return super().formfield_for_foreignkey(db_field, request, **kwargs) class EventAdmin(admin.ModelAdmin): diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index 25a1e00827..8178cb8bcc 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -1088,7 +1088,7 @@ class AggregateTestCase(TestCase): class MyMax(Max): def as_sql(self, compiler, connection): self.set_source_expressions(self.get_source_expressions()[0:1]) - return super(MyMax, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) with self.assertRaisesMessage(FieldError, "Cannot compute Max('id__max'): 'id__max' is an aggregate"): Book.objects.annotate(Max('id')).annotate(my_max=MyMax('id__max', 'price')) @@ -1097,7 +1097,7 @@ class AggregateTestCase(TestCase): class MyMax(Max): def as_sql(self, compiler, connection): self.set_source_expressions(self.get_source_expressions()[0:1]) - return super(MyMax, self).as_sql(compiler, connection) + return super().as_sql(compiler, connection) with self.assertRaisesMessage(TypeError, 'Complex aggregates require an alias'): Book.objects.aggregate(MyMax('pages', 'price')) @@ -1172,7 +1172,7 @@ class AggregateTestCase(TestCase): function = 'GREATEST' def as_sqlite(self, compiler, connection): - return super(Greatest, self).as_sql(compiler, connection, function='MAX') + return super().as_sql(compiler, connection, function='MAX') qs = Publisher.objects.annotate( price_or_median=Greatest(Avg('book__rating'), Avg('book__price')) diff --git a/tests/auth_tests/client.py b/tests/auth_tests/client.py index 004101108b..8f09f115cd 100644 --- a/tests/auth_tests/client.py +++ b/tests/auth_tests/client.py @@ -34,8 +34,8 @@ class PasswordResetConfirmClient(Client): def get(self, path, *args, **kwargs): redirect_url = self._get_password_reset_confirm_redirect_url(path) - return super(PasswordResetConfirmClient, self).get(redirect_url, *args, **kwargs) + return super().get(redirect_url, *args, **kwargs) def post(self, path, *args, **kwargs): redirect_url = self._get_password_reset_confirm_redirect_url(path) - return super(PasswordResetConfirmClient, self).post(redirect_url, *args, **kwargs) + return super().post(redirect_url, *args, **kwargs) diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py index 3d929698c9..0c516dda34 100644 --- a/tests/auth_tests/test_auth_backends.py +++ b/tests/auth_tests/test_auth_backends.py @@ -27,7 +27,7 @@ class CountingMD5PasswordHasher(MD5PasswordHasher): def encode(self, *args, **kwargs): type(self).calls += 1 - return super(CountingMD5PasswordHasher, self).encode(*args, **kwargs) + return super().encode(*args, **kwargs) class BaseModelBackendTest: diff --git a/tests/auth_tests/test_deprecated_views.py b/tests/auth_tests/test_deprecated_views.py index 285638027e..ba43140ebe 100644 --- a/tests/auth_tests/test_deprecated_views.py +++ b/tests/auth_tests/test_deprecated_views.py @@ -332,7 +332,7 @@ class UUIDUserPasswordResetTest(CustomUserPasswordResetTest): username='foo', password='foo', ) - return super(UUIDUserPasswordResetTest, self)._test_confirm_start() + return super()._test_confirm_start() @ignore_warnings(category=RemovedInDjango21Warning) diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py index abd5b0f8df..24343ea5f5 100644 --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -564,7 +564,7 @@ class UserChangeFormTest(TestDataMixin, TestCase): class MyUserForm(UserChangeForm): def __init__(self, *args, **kwargs): - super(MyUserForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['groups'].help_text = 'These groups give users different permissions' class Meta(UserChangeForm.Meta): @@ -645,7 +645,7 @@ class PasswordResetFormTest(TestDataMixin, TestCase): @classmethod def setUpClass(cls): - super(PasswordResetFormTest, cls).setUpClass() + super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() diff --git a/tests/auth_tests/test_remote_user.py b/tests/auth_tests/test_remote_user.py index e03e0a3b95..2a1ebbb569 100644 --- a/tests/auth_tests/test_remote_user.py +++ b/tests/auth_tests/test_remote_user.py @@ -218,7 +218,7 @@ class RemoteUserCustomTest(RemoteUserTest): The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address. """ - super(RemoteUserCustomTest, self).test_known_user() + super().test_known_user() self.assertEqual(User.objects.get(username='knownuser').email, '') self.assertEqual(User.objects.get(username='knownuser2').email, '') @@ -226,7 +226,7 @@ class RemoteUserCustomTest(RemoteUserTest): """ The unknown user created should be configured with an email address. """ - super(RemoteUserCustomTest, self).test_unknown_user() + super().test_unknown_user() newuser = User.objects.get(username='newuser') self.assertEqual(newuser.email, 'user@example.com') diff --git a/tests/auth_tests/test_views.py b/tests/auth_tests/test_views.py index 1e18e0c73b..76d167fa40 100644 --- a/tests/auth_tests/test_views.py +++ b/tests/auth_tests/test_views.py @@ -411,7 +411,7 @@ class UUIDUserPasswordResetTest(CustomUserPasswordResetTest): username='foo', password='foo', ) - return super(UUIDUserPasswordResetTest, self)._test_confirm_start() + return super()._test_confirm_start() class ChangePasswordTest(AuthViewsTestCase): diff --git a/tests/auth_tests/urls.py b/tests/auth_tests/urls.py index 35bdbbb3a8..392355f9b3 100644 --- a/tests/auth_tests/urls.py +++ b/tests/auth_tests/urls.py @@ -15,7 +15,7 @@ from django.views.decorators.cache import never_cache class CustomRequestAuthenticationForm(AuthenticationForm): def __init__(self, request, *args, **kwargs): assert isinstance(request, HttpRequest) - super(CustomRequestAuthenticationForm, self).__init__(request, *args, **kwargs) + super().__init__(request, *args, **kwargs) @never_cache diff --git a/tests/auth_tests/urls_custom_user_admin.py b/tests/auth_tests/urls_custom_user_admin.py index 94039dfa57..59b80d04d7 100644 --- a/tests/auth_tests/urls_custom_user_admin.py +++ b/tests/auth_tests/urls_custom_user_admin.py @@ -12,7 +12,7 @@ class CustomUserAdmin(UserAdmin): # integer manually to avoid causing an error. original_pk = request.user.pk request.user.pk = 1 - super(CustomUserAdmin, self).log_change(request, object, message) + super().log_change(request, object, message) request.user.pk = original_pk diff --git a/tests/basic/tests.py b/tests/basic/tests.py index 544a862766..571088da40 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -641,7 +641,7 @@ class SelectOnSaveTests(TestCase): def _update(self, *args, **kwargs): FakeQuerySet.called = True - super(FakeQuerySet, self)._update(*args, **kwargs) + super()._update(*args, **kwargs) return 0 try: diff --git a/tests/builtin_server/tests.py b/tests/builtin_server/tests.py index a294339f85..73e3d0c07e 100644 --- a/tests/builtin_server/tests.py +++ b/tests/builtin_server/tests.py @@ -34,7 +34,7 @@ class ServerHandler(simple_server.ServerHandler): self._flush() def error_output(self, environ, start_response): - super(ServerHandler, self).error_output(environ, start_response) + super().error_output(environ, start_response) return ['\n'.join(traceback.format_exception(*sys.exc_info()))] @@ -45,7 +45,7 @@ class DummyHandler: class FileWrapperHandler(ServerHandler): def __init__(self, *args, **kwargs): - super(FileWrapperHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.request_handler = DummyHandler() self._used_sendfile = False @@ -97,13 +97,13 @@ class WriteChunkCounterHandler(ServerHandler): """ def __init__(self, *args, **kwargs): - super(WriteChunkCounterHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.request_handler = DummyHandler() self.headers_written = False self.write_chunk_counter = 0 def send_headers(self): - super(WriteChunkCounterHandler, self).send_headers() + super().send_headers() self.headers_written = True def _write(self, data): diff --git a/tests/cache/tests.py b/tests/cache/tests.py index 7c61837ab0..d519080c9a 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -949,12 +949,12 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase): def setUp(self): # The super calls needs to happen first for the settings override. - super(DBCacheTests, self).setUp() + super().setUp() self.create_table() def tearDown(self): # The super call needs to happen first because it uses the database. - super(DBCacheTests, self).tearDown() + super().tearDown() self.drop_table() def create_table(self): @@ -1074,7 +1074,7 @@ class PicklingSideEffect: class LocMemCacheTests(BaseCacheTests, TestCase): def setUp(self): - super(LocMemCacheTests, self).setUp() + super().setUp() # LocMem requires a hack to make the other caches # share a data store with the 'normal' cache. @@ -1321,7 +1321,7 @@ class FileBasedCacheTests(BaseCacheTests, TestCase): """ def setUp(self): - super(FileBasedCacheTests, self).setUp() + super().setUp() self.dirname = tempfile.mkdtemp() # Caches location cannot be modified through override_settings / modify_settings, # hence settings are manipulated directly here and the setting_changed signal @@ -1331,7 +1331,7 @@ class FileBasedCacheTests(BaseCacheTests, TestCase): setting_changed.send(self.__class__, setting='CACHES', enter=False) def tearDown(self): - super(FileBasedCacheTests, self).tearDown() + super().tearDown() # Call parent first, as cache.clear() may recreate cache base directory shutil.rmtree(self.dirname) @@ -1962,7 +1962,7 @@ def csrf_view(request): class CacheMiddlewareTest(SimpleTestCase): def setUp(self): - super(CacheMiddlewareTest, self).setUp() + super().setUp() self.factory = RequestFactory() self.default_cache = caches['default'] self.other_cache = caches['other'] @@ -1970,7 +1970,7 @@ class CacheMiddlewareTest(SimpleTestCase): def tearDown(self): self.default_cache.clear() self.other_cache.clear() - super(CacheMiddlewareTest, self).tearDown() + super().tearDown() def test_constructor(self): """ diff --git a/tests/check_framework/test_templates.py b/tests/check_framework/test_templates.py index 918e0fcbdf..494dab0192 100644 --- a/tests/check_framework/test_templates.py +++ b/tests/check_framework/test_templates.py @@ -59,7 +59,7 @@ class CheckTemplateStringIfInvalidTest(SimpleTestCase): @classmethod def setUpClass(cls): - super(CheckTemplateStringIfInvalidTest, cls).setUpClass() + super().setUpClass() cls.error1 = copy(E002) cls.error2 = copy(E002) string_if_invalid1 = cls.TEMPLATES_STRING_IF_INVALID[0]['OPTIONS']['string_if_invalid'] diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py index f68b0f037b..3531939a73 100644 --- a/tests/csrf_tests/tests.py +++ b/tests/csrf_tests/tests.py @@ -27,7 +27,7 @@ class TestingHttpRequest(HttpRequest): more easily """ def __init__(self): - super(TestingHttpRequest, self).__init__() + super().__init__() # A real session backend isn't needed. self.session = {} @@ -432,7 +432,7 @@ class CsrfViewMiddlewareTestMixin: HttpRequest that can raise an IOError when accessing POST data """ def __init__(self, token, raise_error): - super(CsrfPostRequest, self).__init__() + super().__init__() self.method = 'POST' self.raise_error = False diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py index 7b8cca6646..4a477b4687 100644 --- a/tests/custom_lookups/tests.py +++ b/tests/custom_lookups/tests.py @@ -145,13 +145,13 @@ class SQLFuncMixin: class SQLFuncLookup(SQLFuncMixin, models.Lookup): def __init__(self, name, *args, **kwargs): - super(SQLFuncLookup, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.name = name class SQLFuncTransform(SQLFuncMixin, models.Transform): def __init__(self, name, *args, **kwargs): - super(SQLFuncTransform, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.name = name @@ -173,13 +173,13 @@ class CustomField(models.TextField): if lookup_name.startswith('lookupfunc_'): key, name = lookup_name.split('_', 1) return SQLFuncFactory(key, name) - return super(CustomField, self).get_lookup(lookup_name) + return super().get_lookup(lookup_name) def get_transform(self, lookup_name): if lookup_name.startswith('transformfunc_'): key, name = lookup_name.split('_', 1) return SQLFuncFactory(key, name) - return super(CustomField, self).get_transform(lookup_name) + return super().get_transform(lookup_name) class CustomModel(models.Model): @@ -490,11 +490,11 @@ class TrackCallsYearTransform(YearTransform): def get_lookup(self, lookup_name): self.call_order.append('lookup') - return super(TrackCallsYearTransform, self).get_lookup(lookup_name) + return super().get_lookup(lookup_name) def get_transform(self, lookup_name): self.call_order.append('transform') - return super(TrackCallsYearTransform, self).get_transform(lookup_name) + return super().get_transform(lookup_name) class LookupTransformCallOrderTests(TestCase): diff --git a/tests/custom_managers/models.py b/tests/custom_managers/models.py index c5f224ea51..f90425db3c 100644 --- a/tests/custom_managers/models.py +++ b/tests/custom_managers/models.py @@ -22,12 +22,12 @@ class PersonManager(models.Manager): class PublishedBookManager(models.Manager): def get_queryset(self): - return super(PublishedBookManager, self).get_queryset().filter(is_published=True) + return super().get_queryset().filter(is_published=True) class CustomQuerySet(models.QuerySet): def filter(self, *args, **kwargs): - queryset = super(CustomQuerySet, self).filter(fun=True) + queryset = super().filter(fun=True) queryset._filter_CustomQuerySet = True return queryset @@ -48,11 +48,11 @@ class CustomQuerySet(models.QuerySet): class BaseCustomManager(models.Manager): def __init__(self, arg): - super(BaseCustomManager, self).__init__() + super().__init__() self.init_arg = arg def filter(self, *args, **kwargs): - queryset = super(BaseCustomManager, self).filter(fun=True) + queryset = super().filter(fun=True) queryset._filter_CustomManager = True return queryset @@ -66,23 +66,23 @@ CustomManager = BaseCustomManager.from_queryset(CustomQuerySet) class CustomInitQuerySet(models.QuerySet): # QuerySet with an __init__() method that takes an additional argument. def __init__(self, custom_optional_arg=None, model=None, query=None, using=None, hints=None): - super(CustomInitQuerySet, self).__init__(model=model, query=query, using=using, hints=hints) + super().__init__(model=model, query=query, using=using, hints=hints) class DeconstructibleCustomManager(BaseCustomManager.from_queryset(CustomQuerySet)): def __init__(self, a, b, c=1, d=2): - super(DeconstructibleCustomManager, self).__init__(a) + super().__init__(a) class FunPeopleManager(models.Manager): def get_queryset(self): - return super(FunPeopleManager, self).get_queryset().filter(fun=True) + return super().get_queryset().filter(fun=True) class BoringPeopleManager(models.Manager): def get_queryset(self): - return super(BoringPeopleManager, self).get_queryset().filter(fun=False) + return super().get_queryset().filter(fun=False) class Person(models.Model): @@ -151,7 +151,7 @@ class Book(models.Model): class FastCarManager(models.Manager): def get_queryset(self): - return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150) + return super().get_queryset().filter(top_speed__gt=150) class Car(models.Model): @@ -179,7 +179,7 @@ class FastCarAsDefault(Car): class RestrictedManager(models.Manager): def get_queryset(self): - return super(RestrictedManager, self).get_queryset().filter(is_public=True) + return super().get_queryset().filter(is_public=True) class RelatedModel(models.Model): diff --git a/tests/custom_pk/fields.py b/tests/custom_pk/fields.py index 2be2288ed8..78bb463fce 100644 --- a/tests/custom_pk/fields.py +++ b/tests/custom_pk/fields.py @@ -24,7 +24,7 @@ class MyAutoField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 10 - super(MyAutoField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def pre_save(self, instance, add): value = getattr(instance, self.attname, None) diff --git a/tests/defer/models.py b/tests/defer/models.py index dbdce0b025..fc14f43393 100644 --- a/tests/defer/models.py +++ b/tests/defer/models.py @@ -43,4 +43,4 @@ class RefreshPrimaryProxy(Primary): deferred_fields = self.get_deferred_fields() if fields.intersection(deferred_fields): fields = fields.union(deferred_fields) - super(RefreshPrimaryProxy, self).refresh_from_db(using, fields, **kwargs) + super().refresh_from_db(using, fields, **kwargs) diff --git a/tests/deprecation/tests.py b/tests/deprecation/tests.py index 1afd52f943..ef0284b378 100644 --- a/tests/deprecation/tests.py +++ b/tests/deprecation/tests.py @@ -85,7 +85,7 @@ class RenameMethodsTests(SimpleTestCase): class Deprecated(Renamed): def old(self): - super(Deprecated, self).old() + super().old() warnings.simplefilter('always') deprecated = Deprecated() deprecated.new() @@ -115,7 +115,7 @@ class RenameMethodsTests(SimpleTestCase): class Renamed(Deprecated): def new(self): - super(Renamed, self).new() + super().new() warnings.simplefilter('always') renamed = Renamed() renamed.new() @@ -140,11 +140,11 @@ class RenameMethodsTests(SimpleTestCase): class RenamedMixin: def new(self): - super(RenamedMixin, self).new() + super().new() class DeprecatedMixin: def old(self): - super(DeprecatedMixin, self).old() + super().old() class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): pass diff --git a/tests/extra_regress/models.py b/tests/extra_regress/models.py index 1a5c2dedeb..b069affccd 100644 --- a/tests/extra_regress/models.py +++ b/tests/extra_regress/models.py @@ -14,12 +14,12 @@ class RevisionableModel(models.Model): return "%s (%s, %s)" % (self.title, self.id, self.base.id) def save(self, *args, **kwargs): - super(RevisionableModel, self).save(*args, **kwargs) + super().save(*args, **kwargs) if not self.base: self.base = self kwargs.pop('force_insert', None) kwargs.pop('force_update', None) - super(RevisionableModel, self).save(*args, **kwargs) + super().save(*args, **kwargs) def new_revision(self): new_revision = copy.copy(self) diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index ba77622067..baa6098b09 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -564,7 +564,7 @@ class CustomStorageTests(FileStorageTests): class DiscardingFalseContentStorage(FileSystemStorage): def _save(self, name, content): if content: - return super(DiscardingFalseContentStorage, self)._save(name, content) + return super()._save(name, content) return '' @@ -804,7 +804,7 @@ class FileFieldStorageTests(TestCase): class SlowFile(ContentFile): def chunks(self): time.sleep(1) - return super(ContentFile, self).chunks() + return super().chunks() class FileSaveRaceConditionTest(SimpleTestCase): diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index 827083412e..44a7272753 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -28,14 +28,14 @@ class FileUploadTests(TestCase): @classmethod def setUpClass(cls): - super(FileUploadTests, cls).setUpClass() + super().setUpClass() if not os.path.isdir(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT) - super(FileUploadTests, cls).tearDownClass() + super().tearDownClass() def test_simple_upload(self): with open(__file__, 'rb') as fp: @@ -475,7 +475,7 @@ class FileUploadTests(TestCase): class POSTAccessingHandler(client.ClientHandler): """A handler that'll access POST during an exception.""" def handle_uncaught_exception(self, request, resolver, exc_info): - ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info) + ret = super().handle_uncaught_exception(request, resolver, exc_info) request.POST # evaluate return ret @@ -546,14 +546,14 @@ class DirectoryCreationTests(SimpleTestCase): """ @classmethod def setUpClass(cls): - super(DirectoryCreationTests, cls).setUpClass() + super().setUpClass() if not os.path.isdir(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT) - super(DirectoryCreationTests, cls).tearDownClass() + super().tearDownClass() def setUp(self): self.obj = FileModel() diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py index b69cc751cb..7c6199fd16 100644 --- a/tests/file_uploads/uploadhandler.py +++ b/tests/file_uploads/uploadhandler.py @@ -14,7 +14,7 @@ class QuotaUploadHandler(FileUploadHandler): QUOTA = 5 * 2 ** 20 # 5 MB def __init__(self, request=None): - super(QuotaUploadHandler, self).__init__(request) + super().__init__(request) self.total_upload = 0 def receive_data_chunk(self, raw_data, start): diff --git a/tests/fixtures/models.py b/tests/fixtures/models.py index b3ebb8fc5d..07ef1587d9 100644 --- a/tests/fixtures/models.py +++ b/tests/fixtures/models.py @@ -80,7 +80,7 @@ class Person(models.Model): class SpyManager(PersonManager): def get_queryset(self): - return super(SpyManager, self).get_queryset().filter(cover_blown=False) + return super().get_queryset().filter(cover_blown=False) class Spy(Person): diff --git a/tests/flatpages_tests/test_sitemaps.py b/tests/flatpages_tests/test_sitemaps.py index 10076798c0..62522b343e 100644 --- a/tests/flatpages_tests/test_sitemaps.py +++ b/tests/flatpages_tests/test_sitemaps.py @@ -17,7 +17,7 @@ class FlatpagesSitemapTests(TestCase): @classmethod def setUpClass(cls): - super(FlatpagesSitemapTests, cls).setUpClass() + super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() diff --git a/tests/foreign_object/models/article.py b/tests/foreign_object/models/article.py index 940ec003fb..851029efa1 100644 --- a/tests/foreign_object/models/article.py +++ b/tests/foreign_object/models/article.py @@ -39,7 +39,7 @@ class ActiveTranslationField(models.ForeignObject): return {'lang': get_language()} def contribute_to_class(self, cls, name): - super(ActiveTranslationField, self).contribute_to_class(cls, name) + super().contribute_to_class(cls, name) setattr(cls, self.name, ArticleTranslationDescriptor(self)) diff --git a/tests/foreign_object/models/empty_join.py b/tests/foreign_object/models/empty_join.py index 5b58ffdafc..4ad1ad688b 100644 --- a/tests/foreign_object/models/empty_join.py +++ b/tests/foreign_object/models/empty_join.py @@ -36,7 +36,7 @@ class StartsWithRelation(models.ForeignObject): def __init__(self, *args, **kwargs): kwargs['on_delete'] = models.DO_NOTHING - super(StartsWithRelation, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) @property def field(self): @@ -64,7 +64,7 @@ class StartsWithRelation(models.ForeignObject): return [PathInfo(from_opts, to_opts, (to_opts.pk,), self.remote_field, False, False)] def contribute_to_class(self, cls, name, private_only=False): - super(StartsWithRelation, self).contribute_to_class(cls, name, private_only) + super().contribute_to_class(cls, name, private_only) setattr(cls, self.name, ReverseManyToOneDescriptor(self)) diff --git a/tests/forms_tests/field_tests/test_base.py b/tests/forms_tests/field_tests/test_base.py index 721c0a935a..4ddbea3414 100644 --- a/tests/forms_tests/field_tests/test_base.py +++ b/tests/forms_tests/field_tests/test_base.py @@ -12,11 +12,11 @@ class BasicFieldsTests(SimpleTestCase): class A: def __init__(self): self.class_a_var = True - super(A, self).__init__() + super().__init__() class ComplexField(Field, A): def __init__(self): - super(ComplexField, self).__init__() + super().__init__() f = ComplexField() self.assertTrue(f.class_a_var) diff --git a/tests/forms_tests/field_tests/test_multivaluefield.py b/tests/forms_tests/field_tests/test_multivaluefield.py index e7d161fb5b..1395be6cd0 100644 --- a/tests/forms_tests/field_tests/test_multivaluefield.py +++ b/tests/forms_tests/field_tests/test_multivaluefield.py @@ -17,7 +17,7 @@ class ComplexMultiWidget(MultiWidget): SelectMultiple(choices=beatles), SplitDateTimeWidget(), ) - super(ComplexMultiWidget, self).__init__(widgets, attrs) + super().__init__(widgets, attrs) def decompress(self, value): if value: @@ -40,7 +40,7 @@ class ComplexField(MultiValueField): MultipleChoiceField(choices=beatles), SplitDateTimeField(), ) - super(ComplexField, self).__init__(fields, required, widget, label, initial) + super().__init__(fields, required, widget, label, initial) def compress(self, data_list): if data_list: @@ -57,7 +57,7 @@ class MultiValueFieldTest(SimpleTestCase): @classmethod def setUpClass(cls): cls.field = ComplexField(widget=ComplexMultiWidget()) - super(MultiValueFieldTest, cls).setUpClass() + super().setUpClass() def test_clean(self): self.assertEqual( diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index 2a1ec44f66..19f1927824 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -1231,7 +1231,7 @@ value="Should escape < & > and <script>alert('xss')</ last_name = CharField() def __init__(self, *args, **kwargs): - super(Person, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['birthday'] = DateField() p = Person(auto_id=False) @@ -1302,7 +1302,7 @@ value="Should escape < & > and <script>alert('xss')</ last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): - super(Person, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if names_required: self.fields['first_name'].required = True @@ -1329,7 +1329,7 @@ value="Should escape < & > and <script>alert('xss')</ last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): - super(Person, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if name_max_length: self.fields['first_name'].max_length = name_max_length @@ -1350,7 +1350,7 @@ value="Should escape < & > and <script>alert('xss')</ gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male'))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): - super(Person, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields['gender'].choices += (('u', 'Unspecified'),) @@ -1540,7 +1540,7 @@ value="Should escape < & > and <script>alert('xss')</ field_order = None def __init__(self, **kwargs): - super(TestFormInit, self).__init__(**kwargs) + super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() @@ -2818,7 +2818,7 @@ Good luck picking a username that doesn't already exist.</p> def __init__(self, fields=(), *args, **kwargs): fields = (CharField(label='First name', max_length=10), CharField(label='Last name', max_length=10)) - super(NameField, self).__init__(fields=fields, *args, **kwargs) + super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return ' '.join(data_list) @@ -2849,7 +2849,7 @@ Good luck picking a username that doesn't already exist.</p> ChoiceField(label='Rank', choices=((1, 1), (2, 2))), CharField(label='Name', max_length=10), ) - super(ChoicesField, self).__init__(fields=fields, *args, **kwargs) + super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) @@ -2864,7 +2864,7 @@ Good luck picking a username that doesn't already exist.</p> class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) - super(DateAgeField, self).__init__(fields=fields, *args, **kwargs) + super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() @@ -2883,7 +2883,7 @@ Good luck picking a username that doesn't already exist.</p> CharField(label='Extension', error_messages={'incomplete': 'Enter an extension.'}), CharField(label='Label', required=False, help_text='E.g. home, work.'), ) - super(PhoneField, self).__init__(fields, *args, **kwargs) + super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: @@ -2964,7 +2964,7 @@ Good luck picking a username that doesn't already exist.</p> # Fake json.loads if value == '{}': return {} - return super(CustomJSONField, self).to_python(value) + return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 3c3228fafc..26d9e15605 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -58,7 +58,7 @@ SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) class CustomKwargForm(Form): def __init__(self, *args, **kwargs): self.custom_kwarg = kwargs.pop('custom_kwarg') - super(CustomKwargForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) class FormsFormsetTestCase(SimpleTestCase): @@ -1056,7 +1056,7 @@ class FormsFormsetTestCase(SimpleTestCase): return reversed(self.forms) def __getitem__(self, idx): - return super(BaseReverseFormSet, self).__getitem__(len(self) - idx - 1) + return super().__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() @@ -1106,7 +1106,7 @@ class FormsFormsetTestCase(SimpleTestCase): class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True - return super(AnotherChoice, self).is_valid() + return super().is_valid() AnotherChoiceFormSet = formset_factory(AnotherChoice) data = { diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py index 72db13ef21..488fe190b2 100644 --- a/tests/forms_tests/tests/test_media.py +++ b/tests/forms_tests/tests/test_media.py @@ -164,7 +164,7 @@ class FormsMediaTestCase(SimpleTestCase): # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): - return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) + return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w5 = MyWidget5() @@ -185,7 +185,7 @@ class FormsMediaTestCase(SimpleTestCase): class MyWidget6(MyWidget1): def _media(self): - return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) + return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w6 = MyWidget6() @@ -405,7 +405,7 @@ class FormsMediaTestCase(SimpleTestCase): class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] - super(MyMultiWidget, self).__init__(widgets, attrs) + super().__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual( diff --git a/tests/forms_tests/widget_tests/base.py b/tests/forms_tests/widget_tests/base.py index 490f033bad..7222910479 100644 --- a/tests/forms_tests/widget_tests/base.py +++ b/tests/forms_tests/widget_tests/base.py @@ -15,7 +15,7 @@ class WidgetTest(SimpleTestCase): cls.django_renderer = DjangoTemplates() cls.jinja2_renderer = Jinja2() if jinja2 else None cls.renderers = [cls.django_renderer] + ([cls.jinja2_renderer] if cls.jinja2_renderer else []) - super(WidgetTest, cls).setUpClass() + super().setUpClass() def check_html(self, widget, name, value, html='', attrs=None, strict=False, **kwargs): assertEqual = self.assertEqual if strict else self.assertHTMLEqual diff --git a/tests/forms_tests/widget_tests/test_multiwidget.py b/tests/forms_tests/widget_tests/test_multiwidget.py index bf9ef38a6b..b19b5ce9cf 100644 --- a/tests/forms_tests/widget_tests/test_multiwidget.py +++ b/tests/forms_tests/widget_tests/test_multiwidget.py @@ -24,7 +24,7 @@ class ComplexMultiWidget(MultiWidget): SelectMultiple(choices=WidgetTest.beatles), SplitDateTimeWidget(), ) - super(ComplexMultiWidget, self).__init__(widgets, attrs) + super().__init__(widgets, attrs) def decompress(self, value): if value: @@ -45,9 +45,7 @@ class ComplexField(MultiValueField): MultipleChoiceField(choices=WidgetTest.beatles), SplitDateTimeField(), ) - super(ComplexField, self).__init__( - fields, required, widget, label, initial, - ) + super().__init__(fields, required, widget, label, initial) def compress(self, data_list): if data_list: @@ -66,7 +64,7 @@ class DeepCopyWidget(MultiWidget): RadioSelect(choices=choices), TextInput, ] - super(DeepCopyWidget, self).__init__(widgets) + super().__init__(widgets) def _set_choices(self, choices): """ diff --git a/tests/from_db_value/models.py b/tests/from_db_value/models.py index fae9565a02..2f2304ff0a 100644 --- a/tests/from_db_value/models.py +++ b/tests/from_db_value/models.py @@ -7,7 +7,7 @@ class Cash(decimal.Decimal): currency = 'USD' def __str__(self): - s = super(Cash, self).__str__(self) + s = super().__str__(self) return '%s %s' % (s, self.currency) @@ -15,7 +15,7 @@ class CashField(models.DecimalField): def __init__(self, **kwargs): kwargs['max_digits'] = 20 kwargs['decimal_places'] = 2 - super(CashField, self).__init__(**kwargs) + super().__init__(**kwargs) def from_db_value(self, value, expression, connection, context): cash = Cash(value) diff --git a/tests/generic_relations/models.py b/tests/generic_relations/models.py index a2f68ff05a..eec40e87a4 100644 --- a/tests/generic_relations/models.py +++ b/tests/generic_relations/models.py @@ -97,7 +97,7 @@ class Mineral(models.Model): class GeckoManager(models.Manager): def get_queryset(self): - return super(GeckoManager, self).get_queryset().filter(has_tail=True) + return super().get_queryset().filter(has_tail=True) class Gecko(models.Model): diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py index 5bfea72cf1..08651adb0e 100644 --- a/tests/generic_relations/tests.py +++ b/tests/generic_relations/tests.py @@ -603,7 +603,7 @@ class GenericInlineFormsetTest(TestCase): class SaveTestForm(forms.ModelForm): def save(self, *args, **kwargs): self.instance.saved_by = "custom method" - return super(SaveTestForm, self).save(*args, **kwargs) + return super().save(*args, **kwargs) Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', form=SaveTestForm) diff --git a/tests/generic_relations_regress/models.py b/tests/generic_relations_regress/models.py index fae8aadaa5..6fca154f15 100644 --- a/tests/generic_relations_regress/models.py +++ b/tests/generic_relations_regress/models.py @@ -138,7 +138,7 @@ class Board(models.Model): class SpecialGenericRelation(GenericRelation): def __init__(self, *args, **kwargs): - super(SpecialGenericRelation, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.editable = True self.save_form_data_calls = 0 diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py index be89592dbc..88c376dddc 100644 --- a/tests/generic_views/test_base.py +++ b/tests/generic_views/test_base.py @@ -41,7 +41,7 @@ class DecoratedDispatchView(SimpleView): @decorator def dispatch(self, request, *args, **kwargs): - return super(DecoratedDispatchView, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) class AboutTemplateView(TemplateView): diff --git a/tests/generic_views/views.py b/tests/generic_views/views.py index 05d5ec2f00..9041ad81a1 100644 --- a/tests/generic_views/views.py +++ b/tests/generic_views/views.py @@ -12,7 +12,7 @@ class CustomTemplateView(generic.TemplateView): template_name = 'generic_views/about.html' def get_context_data(self, **kwargs): - context = super(CustomTemplateView, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) context.update({'key': 'value'}) return context @@ -72,22 +72,14 @@ class BookList(generic.ListView): class CustomPaginator(Paginator): def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True): - super(CustomPaginator, self).__init__( - queryset, - page_size, - orphans=2, - allow_empty_first_page=allow_empty_first_page) + super().__init__(queryset, page_size, orphans=2, allow_empty_first_page=allow_empty_first_page) class AuthorListCustomPaginator(AuthorList): paginate_by = 5 def get_paginator(self, queryset, page_size, orphans=0, allow_empty_first_page=True): - return super(AuthorListCustomPaginator, self).get_paginator( - queryset, - page_size, - orphans=2, - allow_empty_first_page=allow_empty_first_page) + return super().get_paginator(queryset, page_size, orphans=2, allow_empty_first_page=allow_empty_first_page) class ContactView(generic.FormView): @@ -152,7 +144,7 @@ class AuthorUpdate(generic.UpdateView): def get_form(self, *args, **kwargs): self.get_form_called_count += 1 - return super(AuthorUpdate, self).get_form(*args, **kwargs) + return super().get_form(*args, **kwargs) class OneAuthorUpdate(generic.UpdateView): @@ -231,8 +223,7 @@ class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin): class BookDetailGetObjectCustomQueryset(BookDetail): def get_object(self, queryset=None): - return super(BookDetailGetObjectCustomQueryset, self).get_object( - queryset=Book.objects.filter(pk=self.kwargs['pk'])) + return super().get_object(queryset=Book.objects.filter(pk=self.kwargs['pk'])) class CustomMultipleObjectMixinView(generic.list.MultipleObjectMixin, generic.View): @@ -255,7 +246,7 @@ class CustomContextView(generic.detail.SingleObjectMixin, generic.View): def get_context_data(self, **kwargs): context = {'custom_key': 'custom_value'} context.update(kwargs) - return super(CustomContextView, self).get_context_data(**context) + return super().get_context_data(**context) def get_context_object_name(self, obj): return "test_name" diff --git a/tests/get_object_or_404/models.py b/tests/get_object_or_404/models.py index ce74bc04ad..b18918a853 100644 --- a/tests/get_object_or_404/models.py +++ b/tests/get_object_or_404/models.py @@ -22,7 +22,7 @@ class Author(models.Model): class ArticleManager(models.Manager): def get_queryset(self): - return super(ArticleManager, self).get_queryset().filter(authors__name__icontains='sir') + return super().get_queryset().filter(authors__name__icontains='sir') class Article(models.Model): diff --git a/tests/gis_tests/geoapp/models.py b/tests/gis_tests/geoapp/models.py index 83e3242043..363f3deaf0 100644 --- a/tests/gis_tests/geoapp/models.py +++ b/tests/gis_tests/geoapp/models.py @@ -94,7 +94,7 @@ class NonConcreteField(models.IntegerField): return None def get_attname_column(self): - attname, column = super(NonConcreteField, self).get_attname_column() + attname, column = super().get_attname_column() return attname, None diff --git a/tests/gis_tests/geoapp/test_sitemaps.py b/tests/gis_tests/geoapp/test_sitemaps.py index 61e06df728..09df326bc6 100644 --- a/tests/gis_tests/geoapp/test_sitemaps.py +++ b/tests/gis_tests/geoapp/test_sitemaps.py @@ -17,7 +17,7 @@ from .models import City, Country class GeoSitemapTest(TestCase): def setUp(self): - super(GeoSitemapTest, self).setUp() + super().setUp() Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() def assertChildNodes(self, elem, expected): diff --git a/tests/gis_tests/geos_tests/test_geos.py b/tests/gis_tests/geos_tests/test_geos.py index b74d3ab708..c90927c5cc 100644 --- a/tests/gis_tests/geos_tests/test_geos.py +++ b/tests/gis_tests/geos_tests/test_geos.py @@ -1260,7 +1260,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin): class ExtendedPolygon(Polygon): def __init__(self, *args, **kwargs): data = kwargs.pop('data', 0) - super(ExtendedPolygon, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._data = data def __str__(self): diff --git a/tests/gis_tests/geos_tests/test_mutable_list.py b/tests/gis_tests/geos_tests/test_mutable_list.py index 26bdeb8045..4e6a44223d 100644 --- a/tests/gis_tests/geos_tests/test_mutable_list.py +++ b/tests/gis_tests/geos_tests/test_mutable_list.py @@ -14,7 +14,7 @@ class UserListA(ListMixin): def __init__(self, i_list, *args, **kwargs): self._list = self._mytype(i_list) - super(UserListA, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __len__(self): return len(self._list) diff --git a/tests/gis_tests/gis_migrations/test_operations.py b/tests/gis_tests/gis_migrations/test_operations.py index 0c8853a9f3..31301ad4ca 100644 --- a/tests/gis_tests/gis_migrations/test_operations.py +++ b/tests/gis_tests/gis_migrations/test_operations.py @@ -28,7 +28,7 @@ class OperationTestCase(TransactionTestCase): # Delete table after testing if hasattr(self, 'current_state'): self.apply_operations('gis', self.current_state, [migrations.DeleteModel('Neighborhood')]) - super(OperationTestCase, self).tearDown() + super().tearDown() @property def has_spatial_indexes(self): @@ -103,7 +103,7 @@ class OperationTestCase(TransactionTestCase): class OperationTests(OperationTestCase): def setUp(self): - super(OperationTests, self).setUp() + super().setUp() self.set_up_test_model() def test_add_geom_field(self): diff --git a/tests/gis_tests/test_data.py b/tests/gis_tests/test_data.py index 4bec3c677e..adcd57b48b 100644 --- a/tests/gis_tests/test_data.py +++ b/tests/gis_tests/test_data.py @@ -47,7 +47,7 @@ class TestDS(TestObj): # Shapefile is default extension, unless specified otherwise. ext = kwargs.pop('ext', 'shp') self.ds = get_ds_file(name, ext) - super(TestDS, self).__init__(**kwargs) + super().__init__(**kwargs) class TestGeom(TestObj): @@ -72,7 +72,7 @@ class TestGeom(TestObj): ext_ring_cs = tuplize(ext_ring_cs) self.ext_ring_cs = ext_ring_cs - super(TestGeom, self).__init__(**kwargs) + super().__init__(**kwargs) class TestGeomSet: diff --git a/tests/i18n/test_compilation.py b/tests/i18n/test_compilation.py index 7d3215d4a8..db6c813115 100644 --- a/tests/i18n/test_compilation.py +++ b/tests/i18n/test_compilation.py @@ -70,7 +70,7 @@ class MultipleLocaleCompilationTests(MessageCompilationTests): MO_FILE_FR = None def setUp(self): - super(MultipleLocaleCompilationTests, self).setUp() + super().setUp() localedir = os.path.join(self.test_dir, 'locale') self.MO_FILE_HR = os.path.join(localedir, 'hr/LC_MESSAGES/django.mo') self.MO_FILE_FR = os.path.join(localedir, 'fr/LC_MESSAGES/django.mo') @@ -96,7 +96,7 @@ class ExcludedLocaleCompilationTests(MessageCompilationTests): MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' def setUp(self): - super(ExcludedLocaleCompilationTests, self).setUp() + super().setUp() copytree('canned_locale', 'locale') def test_command_help(self): @@ -160,7 +160,7 @@ class ProjectAndAppTests(MessageCompilationTests): class FuzzyTranslationTest(ProjectAndAppTests): def setUp(self): - super(FuzzyTranslationTest, self).setUp() + super().setUp() gettext_module._translations = {} # flush cache or test will be useless def test_nofuzzy_compiling(self): diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index 585feda3ac..69d0236fad 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -468,7 +468,7 @@ class IgnoredExtractorTests(ExtractorTests): class SymlinkExtractorTests(ExtractorTests): def setUp(self): - super(SymlinkExtractorTests, self).setUp() + super().setUp() self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked') def test_symlink(self): @@ -632,7 +632,7 @@ class ExcludedLocaleExtractionTests(ExtractorTests): os.utime(self.PO_FILE % locale, (0, 0)) def setUp(self): - super(ExcludedLocaleExtractionTests, self).setUp() + super().setUp() copytree('canned_locale', 'locale') self._set_times_for_all_po_files() diff --git a/tests/i18n/test_percents.py b/tests/i18n/test_percents.py index bf14e020f5..5ab146a4c2 100644 --- a/tests/i18n/test_percents.py +++ b/tests/i18n/test_percents.py @@ -37,7 +37,7 @@ class ExtractingStringsWithPercentSigns(POFileAssertionMixin, FrenchTestCase): """ def setUp(self): - super(ExtractingStringsWithPercentSigns, self).setUp() + super().setUp() with open(self.PO_FILE, 'r') as fp: self.po_contents = fp.read() diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index 4f4801ba2c..acff0dfc28 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -233,7 +233,7 @@ class TranslationThreadSafetyTests(SimpleTestCase): class FormattingTests(SimpleTestCase): def setUp(self): - super(FormattingTests, self).setUp() + super().setUp() self.n = decimal.Decimal('66666.666') self.f = 99999.999 self.d = datetime.date(2009, 12, 31) @@ -981,7 +981,7 @@ class FormattingTests(SimpleTestCase): class MiscTests(SimpleTestCase): def setUp(self): - super(MiscTests, self).setUp() + super().setUp() self.rf = RequestFactory() @override_settings(LANGUAGE_CODE='de') @@ -1215,12 +1215,12 @@ class MiscTests(SimpleTestCase): class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): - super(ResolutionOrderI18NTests, self).setUp() + super().setUp() activate('de') def tearDown(self): deactivate() - super(ResolutionOrderI18NTests, self).tearDown() + super().tearDown() def assertUgettext(self, msgid, msgstr): result = ugettext(msgid) @@ -1430,7 +1430,7 @@ class UnprefixedDefaultLanguageTests(SimpleTestCase): class CountrySpecificLanguageTests(SimpleTestCase): def setUp(self): - super(CountrySpecificLanguageTests, self).setUp() + super().setUp() self.rf = RequestFactory() def test_check_for_language(self): @@ -1480,12 +1480,12 @@ class CountrySpecificLanguageTests(SimpleTestCase): class TranslationFilesMissing(SimpleTestCase): def setUp(self): - super(TranslationFilesMissing, self).setUp() + super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin - super(TranslationFilesMissing, self).tearDown() + super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None diff --git a/tests/indexes/models.py b/tests/indexes/models.py index 47d413faee..208da32c6e 100644 --- a/tests/indexes/models.py +++ b/tests/indexes/models.py @@ -13,7 +13,7 @@ class CurrentTranslation(models.ForeignObject): kwargs['related_name'] = '+' # Set unique to enable model cache. kwargs['unique'] = True - super(CurrentTranslation, self).__init__(to, on_delete, from_fields, to_fields, **kwargs) + super().__init__(to, on_delete, from_fields, to_fields, **kwargs) class ArticleTranslation(models.Model): diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py index fd51714cda..1769bc0f49 100644 --- a/tests/inline_formsets/tests.py +++ b/tests/inline_formsets/tests.py @@ -194,7 +194,7 @@ class InlineFormsetFactoryTest(TestCase): class PoemModelForm(ModelForm): def __init__(self, *args, **kwargs): assert 'poet' in self._meta.fields - super(PoemModelForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) poet = Poet.objects.create(name='test') poet.poem_set.create(name='first test poem') diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py index 6033cac289..f084feb514 100644 --- a/tests/logging_tests/tests.py +++ b/tests/logging_tests/tests.py @@ -68,13 +68,13 @@ class SetupDefaultLoggingMixin: @classmethod def setUpClass(cls): - super(SetupDefaultLoggingMixin, cls).setUpClass() + super().setUpClass() cls._logging = settings.LOGGING logging.config.dictConfig(DEFAULT_LOGGING) @classmethod def tearDownClass(cls): - super(SetupDefaultLoggingMixin, cls).tearDownClass() + super().tearDownClass() logging.config.dictConfig(cls._logging) diff --git a/tests/mail/custombackend.py b/tests/mail/custombackend.py index ac631a6e1b..fd57777787 100644 --- a/tests/mail/custombackend.py +++ b/tests/mail/custombackend.py @@ -6,7 +6,7 @@ from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): - super(EmailBackend, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.test_outbox = [] def send_messages(self, email_messages): diff --git a/tests/mail/tests.py b/tests/mail/tests.py index f30734d72f..60758a637b 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -990,7 +990,7 @@ class LocmemBackendTests(BaseEmailBackendTests, SimpleTestCase): mail.outbox = [] def tearDown(self): - super(LocmemBackendTests, self).tearDown() + super().tearDown() mail.outbox = [] def test_locmem_shared_messages(self): @@ -1017,7 +1017,7 @@ class FileBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.filebased.EmailBackend' def setUp(self): - super(FileBackendTests, self).setUp() + super().setUp() self.tmp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmp_dir) self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir) @@ -1025,7 +1025,7 @@ class FileBackendTests(BaseEmailBackendTests, SimpleTestCase): def tearDown(self): self._settings_override.disable() - super(FileBackendTests, self).tearDown() + super().tearDown() def flush_mailbox(self): for filename in os.listdir(self.tmp_dir): @@ -1077,7 +1077,7 @@ class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase): email_backend = 'django.core.mail.backends.console.EmailBackend' def setUp(self): - super(ConsoleBackendTests, self).setUp() + super().setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() @@ -1085,7 +1085,7 @@ class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase): del self.stream sys.stdout = self.__stdout del self.__stdout - super(ConsoleBackendTests, self).tearDown() + super().tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() @@ -1214,7 +1214,7 @@ class SMTPBackendTestsBase(SimpleTestCase): @classmethod def setUpClass(cls): - super(SMTPBackendTestsBase, cls).setUpClass() + super().setUpClass() cls.server = FakeSMTPServer(('127.0.0.1', 0), None) cls._settings_override = override_settings( EMAIL_HOST="127.0.0.1", @@ -1226,19 +1226,19 @@ class SMTPBackendTestsBase(SimpleTestCase): def tearDownClass(cls): cls._settings_override.disable() cls.server.stop() - super(SMTPBackendTestsBase, cls).tearDownClass() + super().tearDownClass() class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): email_backend = 'django.core.mail.backends.smtp.EmailBackend' def setUp(self): - super(SMTPBackendTests, self).setUp() + super().setUp() self.server.flush_sink() def tearDown(self): self.server.flush_sink() - super(SMTPBackendTests, self).tearDown() + super().tearDown() def flush_mailbox(self): self.server.flush_sink() @@ -1386,7 +1386,7 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): class MyEmailBackend(smtp.EmailBackend): def __init__(self, *args, **kwargs): kwargs.setdefault('timeout', 42) - super(MyEmailBackend, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) myemailbackend = MyEmailBackend() myemailbackend.open() @@ -1454,7 +1454,7 @@ class SMTPBackendStoppedServerTests(SMTPBackendTestsBase): """ @classmethod def setUpClass(cls): - super(SMTPBackendStoppedServerTests, cls).setUpClass() + super().setUpClass() cls.backend = smtp.EmailBackend(username='', password='') cls.server.stop() diff --git a/tests/managers_regress/models.py b/tests/managers_regress/models.py index 1c274d8704..8d5725c5b7 100644 --- a/tests/managers_regress/models.py +++ b/tests/managers_regress/models.py @@ -11,17 +11,17 @@ from django.db import models class OnlyFred(models.Manager): def get_queryset(self): - return super(OnlyFred, self).get_queryset().filter(name='fred') + return super().get_queryset().filter(name='fred') class OnlyBarney(models.Manager): def get_queryset(self): - return super(OnlyBarney, self).get_queryset().filter(name='barney') + return super().get_queryset().filter(name='barney') class Value42(models.Manager): def get_queryset(self): - return super(Value42, self).get_queryset().filter(value=42) + return super().get_queryset().filter(value=42) class AbstractBase1(models.Model): diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py index 93b8029b2f..cfbdb71a44 100644 --- a/tests/many_to_one/models.py +++ b/tests/many_to_one/models.py @@ -97,7 +97,7 @@ class Relation(models.Model): # Test related objects visibility. class SchoolManager(models.Manager): def get_queryset(self): - return super(SchoolManager, self).get_queryset().filter(is_public=True) + return super().get_queryset().filter(is_public=True) class School(models.Model): diff --git a/tests/messages_tests/base.py b/tests/messages_tests/base.py index 8082d468fe..f713d72ab8 100644 --- a/tests/messages_tests/base.py +++ b/tests/messages_tests/base.py @@ -24,7 +24,7 @@ def add_level_messages(storage): class override_settings_tags(override_settings): def enable(self): - super(override_settings_tags, self).enable() + super().enable() # LEVEL_TAGS is a constant defined in the # django.contrib.messages.storage.base module, so after changing # settings.MESSAGE_TAGS, update that constant also. @@ -32,7 +32,7 @@ class override_settings_tags(override_settings): base.LEVEL_TAGS = utils.get_level_tags() def disable(self): - super(override_settings_tags, self).disable() + super().disable() base.LEVEL_TAGS = self.old_level_tags diff --git a/tests/messages_tests/test_api.py b/tests/messages_tests/test_api.py index 3de6b81b7b..86fd5c6838 100644 --- a/tests/messages_tests/test_api.py +++ b/tests/messages_tests/test_api.py @@ -50,7 +50,7 @@ class CustomRequest: def __getattribute__(self, attr): try: - return super(CustomRequest, self).__getattribute__(attr) + return super().__getattribute__(attr) except AttributeError: return getattr(self._request, attr) @@ -61,5 +61,5 @@ class CustomRequestApiTests(ApiTests): one in Django REST framework. """ def setUp(self): - super(CustomRequestApiTests, self).setUp() + super().setUp() self.request = CustomRequest(self.request) diff --git a/tests/messages_tests/test_fallback.py b/tests/messages_tests/test_fallback.py index bfdae79c4a..ea39f32f32 100644 --- a/tests/messages_tests/test_fallback.py +++ b/tests/messages_tests/test_fallback.py @@ -14,7 +14,7 @@ class FallbackTests(BaseTests, SimpleTestCase): def get_request(self): self.session = {} - request = super(FallbackTests, self).get_request() + request = super().get_request() request.session = self.session return request diff --git a/tests/messages_tests/test_session.py b/tests/messages_tests/test_session.py index 3500d60590..e06ba656fa 100644 --- a/tests/messages_tests/test_session.py +++ b/tests/messages_tests/test_session.py @@ -27,7 +27,7 @@ class SessionTests(BaseTests, TestCase): def get_request(self): self.session = {} - request = super(SessionTests, self).get_request() + request = super().get_request() request.session = self.session return request diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index bd2ba89848..2f8954b4cc 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -406,7 +406,7 @@ class BrokenLinkEmailsMiddlewareTest(SimpleTestCase): def is_ignorable_request(self, request, uri, domain, referer): '''Check user-agent in addition to normal checks.''' - if super(SubclassedMiddleware, self).is_ignorable_request(request, uri, domain, referer): + if super().is_ignorable_request(request, uri, domain, referer): return True user_agent = request.META['HTTP_USER_AGENT'] return any(pattern.search(user_agent) for pattern in self.ignored_user_agent_patterns) diff --git a/tests/migrations/models.py b/tests/migrations/models.py index 51679e56bb..440aa582d6 100644 --- a/tests/migrations/models.py +++ b/tests/migrations/models.py @@ -56,7 +56,7 @@ class FoodQuerySet(models.query.QuerySet): class BaseFoodManager(models.Manager): def __init__(self, a, b, c=1, d=2): - super(BaseFoodManager, self).__init__() + super().__init__() self.args = (a, b, c, d) diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index cacbcab743..d5d31b7c7c 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -628,14 +628,14 @@ class MakeMigrationsTests(MigrationTestBase): """ def setUp(self): - super(MakeMigrationsTests, self).setUp() + super().setUp() self._old_models = apps.app_configs['migrations'].models.copy() def tearDown(self): apps.app_configs['migrations'].models = self._old_models apps.all_models['migrations'] = self._old_models apps.clear_cache() - super(MakeMigrationsTests, self).tearDown() + super().tearDown() def test_files_content(self): self.assertTableNotExists("migrations_unicodemodel") diff --git a/tests/model_fields/models.py b/tests/model_fields/models.py index 4830fb9ed2..134d200be9 100644 --- a/tests/model_fields/models.py +++ b/tests/model_fields/models.py @@ -229,11 +229,11 @@ if Image: """ def __init__(self, *args, **kwargs): self.was_opened = False - super(TestImageFieldFile, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def open(self): self.was_opened = True - super(TestImageFieldFile, self).open() + super().open() class TestImageField(ImageField): attr_class = TestImageFieldFile diff --git a/tests/model_fields/test_field_flags.py b/tests/model_fields/test_field_flags.py index ff6f595e27..26a345ea5c 100644 --- a/tests/model_fields/test_field_flags.py +++ b/tests/model_fields/test_field_flags.py @@ -75,7 +75,7 @@ FLAG_PROPERTIES_FOR_RELATIONS = ( class FieldFlagsTests(test.SimpleTestCase): @classmethod def setUpClass(cls): - super(FieldFlagsTests, cls).setUpClass() + super().setUpClass() cls.fields = ( list(AllFieldsModel._meta.fields) + list(AllFieldsModel._meta.private_fields) diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py index c1c97270fc..6ed8b2ca06 100644 --- a/tests/model_forms/models.py +++ b/tests/model_forms/models.py @@ -71,7 +71,7 @@ class Article(models.Model): def save(self, *args, **kwargs): if not self.id: self.created = datetime.date.today() - return super(Article, self).save(*args, **kwargs) + return super().save(*args, **kwargs) def __str__(self): return self.headline @@ -322,7 +322,7 @@ class BigInt(models.Model): class MarkupField(models.CharField): def __init__(self, *args, **kwargs): kwargs["max_length"] = 20 - super(MarkupField, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def formfield(self, **kwargs): # don't allow this field to be used in form (real use-case might be @@ -418,11 +418,11 @@ class Photo(models.Model): # Support code for the tests; this keeps track of how many times save() # gets called on each instance. def __init__(self, *args, **kwargs): - super(Photo, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._savecount = 0 def save(self, force_insert=False, force_update=False): - super(Photo, self).save(force_insert, force_update) + super().save(force_insert, force_update) self._savecount += 1 @@ -439,7 +439,7 @@ class StrictAssignmentFieldSpecific(models.Model): def __setattr__(self, key, value): if self._should_error is True: raise ValidationError(message={key: "Cannot set attribute"}, code='invalid') - super(StrictAssignmentFieldSpecific, self).__setattr__(key, value) + super().__setattr__(key, value) class StrictAssignmentAll(models.Model): @@ -449,7 +449,7 @@ class StrictAssignmentAll(models.Model): def __setattr__(self, key, value): if self._should_error is True: raise ValidationError(message="Cannot set attribute", code='invalid') - super(StrictAssignmentAll, self).__setattr__(key, value) + super().__setattr__(key, value) # A model with ForeignKey(blank=False, null=True) diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index 3c8f7ed108..9dd8e79513 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -216,7 +216,7 @@ class ModelFormBaseTest(TestCase): fields = '__all__' def __init__(self, *args, **kwargs): - super(FormForTestingIsValid, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['character'].required = False char = Character.objects.create(username='user', @@ -245,7 +245,7 @@ class ModelFormBaseTest(TestCase): fields = '__all__' def __init__(self, *args, **kwargs): - super(AwardForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['character'].required = False character = Character.objects.create(username='user', last_action=datetime.datetime.today()) @@ -2947,7 +2947,7 @@ class LocalizedModelFormTest(TestCase): class CustomMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): - new = super(CustomMetaclass, cls).__new__(cls, name, bases, attrs) + new = super().__new__(cls, name, bases, attrs) new.base_fields = {} return new diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py index 832dbe63ee..3873cb3b27 100644 --- a/tests/model_formsets/tests.py +++ b/tests/model_formsets/tests.py @@ -454,7 +454,7 @@ class ModelFormsetTest(TestCase): class PoetForm(forms.ModelForm): def save(self, commit=True): # change the name to "Vladimir Mayakovsky" just to be a jerk. - author = super(PoetForm, self).save(commit=False) + author = super().save(commit=False) author.name = "Vladimir Mayakovsky" if commit: author.save() @@ -513,7 +513,7 @@ class ModelFormsetTest(TestCase): class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): - super(BaseAuthorFormSet, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.queryset = Author.objects.filter(name__startswith='Charles') AuthorFormSet = modelformset_factory(Author, fields='__all__', formset=BaseAuthorFormSet) @@ -864,7 +864,7 @@ class ModelFormsetTest(TestCase): class PoemForm(forms.ModelForm): def save(self, commit=True): # change the name to "Brooklyn Bridge" just to be a jerk. - poem = super(PoemForm, self).save(commit=False) + poem = super().save(commit=False) poem.name = "Brooklyn Bridge" if commit: poem.save() @@ -995,7 +995,7 @@ class ModelFormsetTest(TestCase): """ class PoemForm2(forms.ModelForm): def save(self, commit=True): - poem = super(PoemForm2, self).save(commit=False) + poem = super().save(commit=False) poem.name = "%s by %s" % (poem.name, poem.poet.name) if commit: poem.save() @@ -1413,7 +1413,7 @@ class ModelFormsetTest(TestCase): fields = "__all__" def __init__(self, **kwargs): - super(MembershipForm, self).__init__(**kwargs) + super().__init__(**kwargs) self.fields['date_joined'].widget = forms.SplitDateTimeWidget() FormSet = inlineformset_factory( diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py index 64d933f90c..26ab9c1ae9 100644 --- a/tests/model_formsets_regress/tests.py +++ b/tests/model_formsets_regress/tests.py @@ -375,7 +375,7 @@ class BaseCustomDeleteFormSet(BaseFormSet): form.should_delete() is called. The formset delete field is also suppressed. """ def add_fields(self, form, index): - super(BaseCustomDeleteFormSet, self).add_fields(form, index) + super().add_fields(form, index) self.can_delete = True if DELETION_FIELD_NAME in form.fields: del form.fields[DELETION_FIELD_NAME] diff --git a/tests/model_inheritance/models.py b/tests/model_inheritance/models.py index 62003f032e..86b1cddb8c 100644 --- a/tests/model_inheritance/models.py +++ b/tests/model_inheritance/models.py @@ -160,7 +160,7 @@ class NamedURL(models.Model): class Mixin: def __init__(self): self.other_attr = 1 - super(Mixin, self).__init__() + super().__init__() class MixinModel(models.Model, Mixin): diff --git a/tests/model_regress/test_pickle.py b/tests/model_regress/test_pickle.py index bbbbb4cef0..a3df362e32 100644 --- a/tests/model_regress/test_pickle.py +++ b/tests/model_regress/test_pickle.py @@ -15,7 +15,7 @@ class ModelPickleTestCase(TestCase): title = models.CharField(max_length=10) def __reduce__(self): - reduce_list = super(MissingDjangoVersion, self).__reduce__() + reduce_list = super().__reduce__() data = reduce_list[-1] del data[DJANGO_VERSION_PICKLE_KEY] return reduce_list @@ -34,7 +34,7 @@ class ModelPickleTestCase(TestCase): title = models.CharField(max_length=10) def __reduce__(self): - reduce_list = super(DifferentDjangoVersion, self).__reduce__() + reduce_list = super().__reduce__() data = reduce_list[-1] data[DJANGO_VERSION_PICKLE_KEY] = '1.0' return reduce_list diff --git a/tests/modeladmin/tests.py b/tests/modeladmin/tests.py index 1cded986fa..b85764a290 100644 --- a/tests/modeladmin/tests.py +++ b/tests/modeladmin/tests.py @@ -320,7 +320,7 @@ class ModelAdminTests(TestCase): def get_form(self, request, obj=None, **kwargs): kwargs['exclude'] = ['bio'] - return super(BandAdmin, self).get_form(request, obj, **kwargs) + return super().get_form(request, obj, **kwargs) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) @@ -343,7 +343,7 @@ class ModelAdminTests(TestCase): def get_formset(self, request, obj=None, **kwargs): kwargs['exclude'] = ['opening_band'] - return super(ConcertInline, self).get_formset(request, obj, **kwargs) + return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] @@ -420,7 +420,7 @@ class ModelAdminTests(TestCase): class AdminConcertForm(forms.ModelForm): def __init__(self, *args, **kwargs): - super(AdminConcertForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields["main_band"].queryset = Band.objects.filter(name='The Doors') class ConcertAdminWithForm(ModelAdmin): @@ -455,7 +455,7 @@ class ModelAdminTests(TestCase): def get_formset(self, request, obj=None, **kwargs): if obj: kwargs['form'] = CustomConcertForm - return super(ConcertInline, self).get_formset(request, obj, **kwargs) + return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] diff --git a/tests/multiple_database/models.py b/tests/multiple_database/models.py index 55247f6e18..3e93bb67bc 100644 --- a/tests/multiple_database/models.py +++ b/tests/multiple_database/models.py @@ -42,11 +42,11 @@ class Person(models.Model): class BookManager(models.Manager): def create(self, *args, **kwargs): kwargs.pop('extra_arg', None) - return super(BookManager, self).create(*args, **kwargs) + return super().create(*args, **kwargs) def get_or_create(self, *args, **kwargs): kwargs.pop('extra_arg', None) - return super(BookManager, self).get_or_create(*args, **kwargs) + return super().get_or_create(*args, **kwargs) class Book(models.Model): diff --git a/tests/one_to_one/models.py b/tests/one_to_one/models.py index 263633347d..5e8b918f25 100644 --- a/tests/one_to_one/models.py +++ b/tests/one_to_one/models.py @@ -96,7 +96,7 @@ class ToFieldPointer(models.Model): # Test related objects visibility. class SchoolManager(models.Manager): def get_queryset(self): - return super(SchoolManager, self).get_queryset().filter(is_public=True) + return super().get_queryset().filter(is_public=True) class School(models.Model): @@ -106,7 +106,7 @@ class School(models.Model): class DirectorManager(models.Manager): def get_queryset(self): - return super(DirectorManager, self).get_queryset().filter(is_temp=False) + return super().get_queryset().filter(is_temp=False) class Director(models.Model): diff --git a/tests/pagination/custom.py b/tests/pagination/custom.py index 77277dca5b..5f3df3c33c 100644 --- a/tests/pagination/custom.py +++ b/tests/pagination/custom.py @@ -6,12 +6,12 @@ class ValidAdjacentNumsPage(Page): def next_page_number(self): if not self.has_next(): return None - return super(ValidAdjacentNumsPage, self).next_page_number() + return super().next_page_number() def previous_page_number(self): if not self.has_previous(): return None - return super(ValidAdjacentNumsPage, self).previous_page_number() + return super().previous_page_number() class ValidAdjacentNumsPaginator(Paginator): diff --git a/tests/postgres_tests/__init__.py b/tests/postgres_tests/__init__.py index dbb913dbba..49f1220888 100644 --- a/tests/postgres_tests/__init__.py +++ b/tests/postgres_tests/__init__.py @@ -13,4 +13,4 @@ class PostgreSQLTestCase(TestCase): from django.contrib.postgres.signals import register_hstore_handler connection_created.disconnect(register_hstore_handler) - super(PostgreSQLTestCase, cls).tearDownClass() + super().tearDownClass() diff --git a/tests/postgres_tests/fields.py b/tests/postgres_tests/fields.py index 14283ccd61..5892a7f71f 100644 --- a/tests/postgres_tests/fields.py +++ b/tests/postgres_tests/fields.py @@ -14,10 +14,10 @@ try: except ImportError: class DummyArrayField(models.Field): def __init__(self, base_field, size=None, **kwargs): - super(DummyArrayField, self).__init__(**kwargs) + super().__init__(**kwargs) def deconstruct(self): - name, path, args, kwargs = super(DummyArrayField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() kwargs.update({ 'base_field': '', 'size': 1, @@ -26,7 +26,7 @@ except ImportError: class DummyJSONField(models.Field): def __init__(self, encoder=None, **kwargs): - super(DummyJSONField, self).__init__(**kwargs) + super().__init__(**kwargs) ArrayField = DummyArrayField BigIntegerRangeField = models.Field diff --git a/tests/postgres_tests/models.py b/tests/postgres_tests/models.py index a77fc4b152..367a32be74 100644 --- a/tests/postgres_tests/models.py +++ b/tests/postgres_tests/models.py @@ -146,7 +146,7 @@ class JSONModel(models.Model): class ArrayFieldSubclass(ArrayField): def __init__(self, *args, **kwargs): - super(ArrayFieldSubclass, self).__init__(models.IntegerField()) + super().__init__(models.IntegerField()) class AggregateTestModel(models.Model): diff --git a/tests/prefetch_related/models.py b/tests/prefetch_related/models.py index c995acb684..a7ac55ce10 100644 --- a/tests/prefetch_related/models.py +++ b/tests/prefetch_related/models.py @@ -97,7 +97,7 @@ class Qualification(models.Model): class TeacherManager(models.Manager): def get_queryset(self): - return super(TeacherManager, self).get_queryset().prefetch_related('qualifications') + return super().get_queryset().prefetch_related('qualifications') class Teacher(models.Model): diff --git a/tests/proxy_models/models.py b/tests/proxy_models/models.py index 93430d615f..2e4679122d 100644 --- a/tests/proxy_models/models.py +++ b/tests/proxy_models/models.py @@ -12,12 +12,12 @@ from django.db import models class PersonManager(models.Manager): def get_queryset(self): - return super(PersonManager, self).get_queryset().exclude(name="fred") + return super().get_queryset().exclude(name="fred") class SubManager(models.Manager): def get_queryset(self): - return super(SubManager, self).get_queryset().exclude(name="wilma") + return super().get_queryset().exclude(name="wilma") class Person(models.Model): diff --git a/tests/queries/models.py b/tests/queries/models.py index 8c20e76dee..592359c796 100644 --- a/tests/queries/models.py +++ b/tests/queries/models.py @@ -51,7 +51,7 @@ class Note(models.Model): return self.note def __init__(self, *args, **kwargs): - super(Note, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Regression for #13227 -- having an attribute that # is unpicklable doesn't stop you from cloning queries # that use objects of that type as an argument. @@ -195,7 +195,7 @@ class LoopZ(models.Model): class CustomManager(models.Manager): def get_queryset(self): - qs = super(CustomManager, self).get_queryset() + qs = super().get_queryset() return qs.filter(public=True, tag__name='t1') @@ -219,7 +219,7 @@ class Detail(models.Model): class MemberManager(models.Manager): def get_queryset(self): - return super(MemberManager, self).get_queryset().select_related("details") + return super().get_queryset().select_related("details") class Member(models.Model): diff --git a/tests/queryset_pickle/models.py b/tests/queryset_pickle/models.py index dbd570a30b..a5c0d15441 100644 --- a/tests/queryset_pickle/models.py +++ b/tests/queryset_pickle/models.py @@ -16,14 +16,14 @@ class Numbers: class PreviousDjangoVersionQuerySet(models.QuerySet): def __getstate__(self): - state = super(PreviousDjangoVersionQuerySet, self).__getstate__() + state = super().__getstate__() state[DJANGO_VERSION_PICKLE_KEY] = '1.0' return state class MissingDjangoVersionQuerySet(models.QuerySet): def __getstate__(self): - state = super(MissingDjangoVersionQuerySet, self).__getstate__() + state = super().__getstate__() del state[DJANGO_VERSION_PICKLE_KEY] return state diff --git a/tests/raw_query/models.py b/tests/raw_query/models.py index 6e996322cc..7e090b7a3f 100644 --- a/tests/raw_query/models.py +++ b/tests/raw_query/models.py @@ -7,7 +7,7 @@ class Author(models.Model): dob = models.DateField() def __init__(self, *args, **kwargs): - super(Author, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Protect against annotations being passed to __init__ -- # this'll make the test suite get angry if annotations aren't # treated differently than fields. diff --git a/tests/save_delete_hooks/models.py b/tests/save_delete_hooks/models.py index 3573112cfa..e7c598aeae 100644 --- a/tests/save_delete_hooks/models.py +++ b/tests/save_delete_hooks/models.py @@ -12,7 +12,7 @@ class Person(models.Model): last_name = models.CharField(max_length=20) def __init__(self, *args, **kwargs): - super(Person, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.data = [] def __str__(self): @@ -21,11 +21,11 @@ class Person(models.Model): def save(self, *args, **kwargs): self.data.append("Before save") # Call the "real" save() method - super(Person, self).save(*args, **kwargs) + super().save(*args, **kwargs) self.data.append("After save") def delete(self): self.data.append("Before deletion") # Call the "real" delete() method - super(Person, self).delete() + super().delete() self.data.append("After deletion") diff --git a/tests/schema/fields.py b/tests/schema/fields.py index 5f2b6ba19c..16a61ee5f6 100644 --- a/tests/schema/fields.py +++ b/tests/schema/fields.py @@ -32,13 +32,13 @@ class CustomManyToManyField(RelatedField): self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." - super(CustomManyToManyField, self).__init__(**kwargs) + super().__init__(**kwargs) def contribute_to_class(self, cls, name, **kwargs): if self.remote_field.symmetrical and ( self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name): self.remote_field.related_name = "%s_rel_+" % name - super(CustomManyToManyField, self).contribute_to_class(cls, name, **kwargs) + super().contribute_to_class(cls, name, **kwargs) if not self.remote_field.through and not cls._meta.abstract and not cls._meta.swapped: self.remote_field.through = create_many_to_many_intermediary_model(self, cls) setattr(cls, self.name, ManyToManyDescriptor(self.remote_field)) diff --git a/tests/serializers/models/base.py b/tests/serializers/models/base.py index 78d832140f..2b7d18d93a 100644 --- a/tests/serializers/models/base.py +++ b/tests/serializers/models/base.py @@ -114,7 +114,7 @@ class Team: class TeamField(models.CharField): def __init__(self): - super(TeamField, self).__init__(max_length=100) + super().__init__(max_length=100) def get_db_prep_save(self, value, connection): return str(value.title) @@ -131,7 +131,7 @@ class TeamField(models.CharField): return self.value_from_object(obj).to_string() def deconstruct(self): - name, path, args, kwargs = super(TeamField, self).deconstruct() + name, path, args, kwargs = super().deconstruct() del kwargs['max_length'] return name, path, args, kwargs diff --git a/tests/serializers/models/data.py b/tests/serializers/models/data.py index f6a1d108f6..14bd644fe1 100644 --- a/tests/serializers/models/data.py +++ b/tests/serializers/models/data.py @@ -277,7 +277,7 @@ class ModifyingSaveData(models.Model): (#4459). """ self.data = 666 - super(ModifyingSaveData, self).save(*args, **kwargs) + super().save(*args, **kwargs) # Tests for serialization of models using inheritance. # Regression for #7202, #7350 diff --git a/tests/serializers/test_json.py b/tests/serializers/test_json.py index 7713e0c3c4..ae671f4847 100644 --- a/tests/serializers/test_json.py +++ b/tests/serializers/test_json.py @@ -86,7 +86,7 @@ class JsonSerializerTestCase(SerializersTestBase, TestCase): def default(self, o): if isinstance(o, decimal.Decimal): return str(o) - return super(CustomJSONEncoder, self).default(o) + return super().default(o) s = serializers.json.Serializer() json_data = s.serialize( diff --git a/tests/serializers/test_yaml.py b/tests/serializers/test_yaml.py index 5a9fa5e873..e876597e9d 100644 --- a/tests/serializers/test_yaml.py +++ b/tests/serializers/test_yaml.py @@ -47,7 +47,7 @@ class NoYamlSerializerTestCase(SimpleTestCase): @classmethod def setUpClass(cls): """Removes imported yaml and stubs importlib.import_module""" - super(NoYamlSerializerTestCase, cls).setUpClass() + super().setUpClass() cls._import_module_mock = YamlImportModuleMock() importlib.import_module = cls._import_module_mock.import_module @@ -58,7 +58,7 @@ class NoYamlSerializerTestCase(SimpleTestCase): @classmethod def tearDownClass(cls): """Puts yaml back if necessary""" - super(NoYamlSerializerTestCase, cls).tearDownClass() + super().tearDownClass() importlib.import_module = cls._import_module_mock._import_module diff --git a/tests/servers/tests.py b/tests/servers/tests.py index d6d0392bcd..27f7f9994f 100644 --- a/tests/servers/tests.py +++ b/tests/servers/tests.py @@ -40,7 +40,7 @@ class LiveServerAddress(LiveServerBase): @classmethod def setUpClass(cls): - super(LiveServerAddress, cls).setUpClass() + super().setUpClass() # put it in a list to prevent descriptor lookups in test cls.live_server_url_test = [cls.live_server_url] diff --git a/tests/sessions_tests/models.py b/tests/sessions_tests/models.py index 7a358595e9..4fa216d9e6 100644 --- a/tests/sessions_tests/models.py +++ b/tests/sessions_tests/models.py @@ -29,7 +29,7 @@ class SessionStore(DBStore): return CustomSession def create_model_instance(self, data): - obj = super(SessionStore, self).create_model_instance(data) + obj = super().create_model_instance(data) try: account_id = int(data.get('_auth_user_id')) diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index 54b8ac53a5..9654c7d9eb 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -508,10 +508,10 @@ class FileSessionTests(SessionTestsMixin, unittest.TestCase): # Reset the file session backend's internal caches if hasattr(self.backend, '_storage_path'): del self.backend._storage_path - super(FileSessionTests, self).setUp() + super().setUp() def tearDown(self): - super(FileSessionTests, self).tearDown() + super().tearDown() settings.SESSION_FILE_PATH = self.original_session_file_path shutil.rmtree(self.temp_session_store) @@ -845,7 +845,7 @@ class CookieSessionTests(SessionTestsMixin, unittest.TestCase): @unittest.expectedFailure def test_actual_expiry(self): # The cookie backend doesn't handle non-default expiry dates, see #19201 - super(CookieSessionTests, self).test_actual_expiry() + super().test_actual_expiry() def test_unpickling_exception(self): # signed_cookies backend should handle unpickle exceptions gracefully diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py index fa51c0af20..d34077c395 100644 --- a/tests/settings_tests/tests.py +++ b/tests/settings_tests/tests.py @@ -108,7 +108,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): - super(ClassDecoratedTestCase, cls).setUpClass() + super().setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self): @@ -127,7 +127,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): Overriding a method on a super class and then calling that method on the super class should not trigger infinite recursion. See #17011. """ - super(ClassDecoratedTestCase, self).test_max_recursion_error() + super().test_max_recursion_error() @modify_settings(ITEMS={'append': 'mother'}) diff --git a/tests/signals/tests.py b/tests/signals/tests.py index c6453b83d0..563f3431cc 100644 --- a/tests/signals/tests.py +++ b/tests/signals/tests.py @@ -283,7 +283,7 @@ class SignalTests(BaseSignalTest): class LazyModelRefTest(BaseSignalTest): def setUp(self): - super(LazyModelRefTest, self).setUp() + super().setUp() self.received = [] def receiver(self, **kwargs): diff --git a/tests/sitemaps_tests/base.py b/tests/sitemaps_tests/base.py index 473ced7d3a..af5f78f327 100644 --- a/tests/sitemaps_tests/base.py +++ b/tests/sitemaps_tests/base.py @@ -22,7 +22,7 @@ class SitemapTestsBase(TestCase): @classmethod def setUpClass(cls): - super(SitemapTestsBase, cls).setUpClass() + super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() diff --git a/tests/staticfiles_tests/cases.py b/tests/staticfiles_tests/cases.py index 2305b34527..593739d401 100644 --- a/tests/staticfiles_tests/cases.py +++ b/tests/staticfiles_tests/cases.py @@ -62,7 +62,7 @@ class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase): all these tests. """ def setUp(self): - super(CollectionTestCase, self).setUp() + super().setUp() temp_dir = tempfile.mkdtemp() # Override the STATIC_ROOT for all tests from setUp to tearDown # rather than as a context manager @@ -74,7 +74,7 @@ class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase): def tearDown(self): self.patched_settings.disable() - super(CollectionTestCase, self).tearDown() + super().tearDown() def run_collectstatic(self, **kwargs): verbosity = kwargs.pop('verbosity', 0) diff --git a/tests/staticfiles_tests/test_finders.py b/tests/staticfiles_tests/test_finders.py index 7df8c50a0d..0b661cb103 100644 --- a/tests/staticfiles_tests/test_finders.py +++ b/tests/staticfiles_tests/test_finders.py @@ -35,7 +35,7 @@ class TestFileSystemFinder(TestFinders, StaticFilesTestCase): Test FileSystemFinder. """ def setUp(self): - super(TestFileSystemFinder, self).setUp() + super().setUp() self.finder = finders.FileSystemFinder() test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt') self.find_first = (os.path.join('test', 'file.txt'), test_file_path) @@ -47,7 +47,7 @@ class TestAppDirectoriesFinder(TestFinders, StaticFilesTestCase): Test AppDirectoriesFinder. """ def setUp(self): - super(TestAppDirectoriesFinder, self).setUp() + super().setUp() self.finder = finders.AppDirectoriesFinder() test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt') self.find_first = (os.path.join('test', 'file1.txt'), test_file_path) @@ -59,7 +59,7 @@ class TestDefaultStorageFinder(TestFinders, StaticFilesTestCase): Test DefaultStorageFinder. """ def setUp(self): - super(TestDefaultStorageFinder, self).setUp() + super().setUp() self.finder = finders.DefaultStorageFinder( storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT)) test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt') diff --git a/tests/staticfiles_tests/test_liveserver.py b/tests/staticfiles_tests/test_liveserver.py index f45a95ba89..264242bbae 100644 --- a/tests/staticfiles_tests/test_liveserver.py +++ b/tests/staticfiles_tests/test_liveserver.py @@ -29,11 +29,11 @@ class LiveServerBase(StaticLiveServerTestCase): # Override settings cls.settings_override = override_settings(**TEST_SETTINGS) cls.settings_override.enable() - super(LiveServerBase, cls).setUpClass() + super().setUpClass() @classmethod def tearDownClass(cls): - super(LiveServerBase, cls).tearDownClass() + super().tearDownClass() # Restore original settings cls.settings_override.disable() @@ -57,14 +57,14 @@ class StaticLiveServerChecks(LiveServerBase): @classmethod def raises_exception(cls): try: - super(StaticLiveServerChecks, cls).setUpClass() + super().setUpClass() raise Exception("The line above should have raised an exception") except ImproperlyConfigured: # This raises ImproperlyConfigured("You're using the staticfiles # app without having set the required STATIC_URL setting.") pass finally: - super(StaticLiveServerChecks, cls).tearDownClass() + super().tearDownClass() def test_test_test(self): # Intentionally empty method so that the test is picked up by the diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py index 5e1f49a5d3..ea58f9afb6 100644 --- a/tests/staticfiles_tests/test_management.py +++ b/tests/staticfiles_tests/test_management.py @@ -161,14 +161,14 @@ class TestCollectionClear(CollectionTestCase): clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt') with open(clear_filepath, 'w') as f: f.write('should be cleared') - super(TestCollectionClear, self).run_collectstatic(clear=True) + super().run_collectstatic(clear=True) def test_cleared_not_found(self): self.assertFileNotFound('cleared.txt') def test_dir_not_exists(self, **kwargs): shutil.rmtree(settings.STATIC_ROOT) - super(TestCollectionClear, self).run_collectstatic(clear=True) + super().run_collectstatic(clear=True) @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.PathNotImplementedStorage') def test_handle_path_notimplemented(self): @@ -234,8 +234,7 @@ class TestCollectionExcludeNoDefaultIgnore(TestDefaults, CollectionTestCase): ``collectstatic`` management command. """ def run_collectstatic(self): - super(TestCollectionExcludeNoDefaultIgnore, self).run_collectstatic( - use_default_ignore_patterns=False) + super().run_collectstatic(use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ @@ -266,7 +265,7 @@ class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase): Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): - super(TestCollectionDryRun, self).run_collectstatic(dry_run=True) + super().run_collectstatic(dry_run=True) class TestCollectionFilesOverride(CollectionTestCase): @@ -308,10 +307,10 @@ class TestCollectionFilesOverride(CollectionTestCase): with extend_sys_path(self.temp_dir): self.settings_with_test_app.enable() - super(TestCollectionFilesOverride, self).setUp() + super().setUp() def tearDown(self): - super(TestCollectionFilesOverride, self).tearDown() + super().tearDown() self.settings_with_test_app.disable() def test_ordering_override(self): @@ -422,7 +421,7 @@ class TestCollectionLinks(TestDefaults, CollectionTestCase): ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self, clear=False, link=True, **kwargs): - super(TestCollectionLinks, self).run_collectstatic(link=link, clear=clear, **kwargs) + super().run_collectstatic(link=link, clear=clear, **kwargs) def test_links_created(self): """ diff --git a/tests/staticfiles_tests/test_storage.py b/tests/staticfiles_tests/test_storage.py index 2bbe912507..7e7b31fa67 100644 --- a/tests/staticfiles_tests/test_storage.py +++ b/tests/staticfiles_tests/test_storage.py @@ -27,7 +27,7 @@ class TestHashedFiles: def setUp(self): self._max_post_process_passes = storage.staticfiles_storage.max_post_process_passes - super(TestHashedFiles, self).setUp() + super().setUp() def tearDown(self): # Clear hashed files to avoid side effects among tests. @@ -305,7 +305,7 @@ class TestExtraPatternsCachedStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference - super(TestExtraPatternsCachedStorage, self).setUp() + super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) @@ -338,7 +338,7 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): Tests for the Cache busting storage """ def setUp(self): - super(TestCollectionManifestStorage, self).setUp() + super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, 'test')) @@ -359,7 +359,7 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict - super(TestCollectionManifestStorage, self).tearDown() + super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files @@ -446,7 +446,7 @@ class TestCollectionSimpleCachedStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference - super(TestCollectionSimpleCachedStorage, self).setUp() + super().setUp() def test_template_tag_return(self): """ @@ -474,7 +474,7 @@ class CustomStaticFilesStorage(storage.StaticFilesStorage): def __init__(self, *args, **kwargs): kwargs['file_permissions_mode'] = 0o640 kwargs['directory_permissions_mode'] = 0o740 - super(CustomStaticFilesStorage, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports chmod.") @@ -489,11 +489,11 @@ class TestStaticFilePermissions(CollectionTestCase): def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) - super(TestStaticFilePermissions, self).setUp() + super().setUp() def tearDown(self): os.umask(self.old_umask) - super(TestStaticFilePermissions, self).tearDown() + super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): @@ -556,12 +556,12 @@ class TestCollectionHashedFilesCache(CollectionTestCase): ) with open(self.testimage_path, 'r+b') as f: self._orig_image_content = f.read() - super(TestCollectionHashedFilesCache, self).setUp() + super().setUp() def tearDown(self): with open(self.testimage_path, 'w+b') as f: f.write(self._orig_image_content) - super(TestCollectionHashedFilesCache, self).tearDown() + super().tearDown() def test_file_change_after_collectstatic(self): finders.get_finder.cache_clear() diff --git a/tests/syndication_tests/feeds.py b/tests/syndication_tests/feeds.py index 87c8d962b7..0805258138 100644 --- a/tests/syndication_tests/feeds.py +++ b/tests/syndication_tests/feeds.py @@ -131,7 +131,7 @@ class TemplateContextFeed(TestRss2Feed): description_template = 'syndication/description_context.html' def get_context_data(self, **kwargs): - context = super(TemplateContextFeed, self).get_context_data(**kwargs) + context = super().get_context_data(**kwargs) context['foo'] = 'bar' return context @@ -164,21 +164,21 @@ class MyCustomAtom1Feed(feedgenerator.Atom1Feed): Test of a custom feed generator class. """ def root_attributes(self): - attrs = super(MyCustomAtom1Feed, self).root_attributes() + attrs = super().root_attributes() attrs['django'] = 'rocks' return attrs def add_root_elements(self, handler): - super(MyCustomAtom1Feed, self).add_root_elements(handler) + super().add_root_elements(handler) handler.addQuickElement('spam', 'eggs') def item_attributes(self, item): - attrs = super(MyCustomAtom1Feed, self).item_attributes(item) + attrs = super().item_attributes(item) attrs['bacon'] = 'yum' return attrs def add_item_elements(self, handler, item): - super(MyCustomAtom1Feed, self).add_item_elements(handler, item) + super().add_item_elements(handler, item) handler.addQuickElement('ministry', 'silly walks') diff --git a/tests/syndication_tests/tests.py b/tests/syndication_tests/tests.py index c9baa6537b..0563fd444c 100644 --- a/tests/syndication_tests/tests.py +++ b/tests/syndication_tests/tests.py @@ -64,7 +64,7 @@ class SyndicationFeedTest(FeedTestCase): """ @classmethod def setUpClass(cls): - super(SyndicationFeedTest, cls).setUpClass() + super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() diff --git a/tests/template_backends/test_dummy.py b/tests/template_backends/test_dummy.py index dededfe390..5e1639cd80 100644 --- a/tests/template_backends/test_dummy.py +++ b/tests/template_backends/test_dummy.py @@ -18,7 +18,7 @@ class TemplateStringsTests(SimpleTestCase): @classmethod def setUpClass(cls): - super(TemplateStringsTests, cls).setUpClass() + super().setUpClass() params = { 'DIRS': [], 'APP_DIRS': True, diff --git a/tests/template_tests/syntax_tests/test_cache.py b/tests/template_tests/syntax_tests/test_cache.py index 7f7a6cd2cb..7dec02eb10 100644 --- a/tests/template_tests/syntax_tests/test_cache.py +++ b/tests/template_tests/syntax_tests/test_cache.py @@ -128,7 +128,7 @@ class CacheTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(libraries={'cache': 'django.templatetags.cache'}) - super(CacheTests, cls).setUpClass() + super().setUpClass() def test_cache_regression_20130(self): t = self.engine.from_string('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}') diff --git a/tests/template_tests/syntax_tests/test_if_changed.py b/tests/template_tests/syntax_tests/test_if_changed.py index bf8a95d8a4..889a24fcd8 100644 --- a/tests/template_tests/syntax_tests/test_if_changed.py +++ b/tests/template_tests/syntax_tests/test_if_changed.py @@ -161,7 +161,7 @@ class IfChangedTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine() - super(IfChangedTests, cls).setUpClass() + super().setUpClass() def test_ifchanged_concurrency(self): """ diff --git a/tests/template_tests/test_callables.py b/tests/template_tests/test_callables.py index 6a361e8409..b72b122deb 100644 --- a/tests/template_tests/test_callables.py +++ b/tests/template_tests/test_callables.py @@ -8,7 +8,7 @@ class CallableVariablesTests(TestCase): @classmethod def setUpClass(cls): cls.engine = Engine() - super(CallableVariablesTests, cls).setUpClass() + super().setUpClass() def test_callable(self): diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py index 8eec22504c..5b788468b5 100644 --- a/tests/template_tests/test_custom.py +++ b/tests/template_tests/test_custom.py @@ -31,7 +31,7 @@ class TagTestCase(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(app_dirs=True, libraries=LIBRARIES) - super(TagTestCase, cls).setUpClass() + super().setUpClass() def verify_tag(self, tag, name): self.assertEqual(tag.__name__, name) @@ -307,7 +307,7 @@ class TemplateTagLoadingTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.egg_dir = os.path.join(ROOT, 'eggs') - super(TemplateTagLoadingTests, cls).setUpClass() + super().setUpClass() def test_load_error(self): msg = ( diff --git a/tests/template_tests/test_loaders.py b/tests/template_tests/test_loaders.py index c36e1ba6be..b90586a078 100644 --- a/tests/template_tests/test_loaders.py +++ b/tests/template_tests/test_loaders.py @@ -99,7 +99,7 @@ class FileSystemLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(dirs=[TEMPLATE_DIR], loaders=['django.template.loaders.filesystem.Loader']) - super(FileSystemLoaderTests, cls).setUpClass() + super().setUpClass() @contextmanager def set_dirs(self, dirs): @@ -213,7 +213,7 @@ class AppDirectoriesLoaderTests(SimpleTestCase): cls.engine = Engine( loaders=['django.template.loaders.app_directories.Loader'], ) - super(AppDirectoriesLoaderTests, cls).setUpClass() + super().setUpClass() @override_settings(INSTALLED_APPS=['template_tests']) def test_get_template(self): @@ -237,7 +237,7 @@ class LocmemLoaderTests(SimpleTestCase): 'index.html': 'index', })], ) - super(LocmemLoaderTests, cls).setUpClass() + super().setUpClass() def test_get_template(self): template = self.engine.get_template('index.html') diff --git a/tests/template_tests/test_logging.py b/tests/template_tests/test_logging.py index e03809d864..802015cf97 100644 --- a/tests/template_tests/test_logging.py +++ b/tests/template_tests/test_logging.py @@ -7,7 +7,7 @@ from django.utils.deprecation import RemovedInDjango21Warning class TestHandler(logging.Handler): def __init__(self): - super(TestHandler, self).__init__() + super().__init__() self.log_record = None def emit(self, record): @@ -88,7 +88,7 @@ class IncludeNodeLoggingTests(BaseTemplateLoggingTestCase): @classmethod def setUpClass(cls): - super(IncludeNodeLoggingTests, cls).setUpClass() + super().setUpClass() cls.engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'child': '{{ raises_exception }}', diff --git a/tests/template_tests/test_nodelist.py b/tests/template_tests/test_nodelist.py index b69e7c063b..35f382a163 100644 --- a/tests/template_tests/test_nodelist.py +++ b/tests/template_tests/test_nodelist.py @@ -9,7 +9,7 @@ class NodelistTest(TestCase): @classmethod def setUpClass(cls): cls.engine = Engine() - super(NodelistTest, cls).setUpClass() + super().setUpClass() def test_for(self): template = self.engine.from_string('{% for i in 1 %}{{ a }}{% endfor %}') diff --git a/tests/test_client_regress/session.py b/tests/test_client_regress/session.py index 461f66b624..ab374d37f0 100644 --- a/tests/test_client_regress/session.py +++ b/tests/test_client_regress/session.py @@ -9,7 +9,7 @@ class SessionStore(SessionBase): This means that saving the session will change the session key. """ def __init__(self, session_key=None): - super(SessionStore, self).__init__(session_key) + super().__init__(session_key) def exists(self, session_key): return False diff --git a/tests/test_runner/runner.py b/tests/test_runner/runner.py index e61de58a93..ac95aac403 100644 --- a/tests/test_runner/runner.py +++ b/tests/test_runner/runner.py @@ -5,9 +5,7 @@ class CustomOptionsTestRunner(DiscoverRunner): def __init__(self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs): - super(CustomOptionsTestRunner, self).__init__( - verbosity=verbosity, interactive=interactive, failfast=failfast, - ) + super().__init__(verbosity=verbosity, interactive=interactive, failfast=failfast) self.option_a = option_a self.option_b = option_b self.option_c = option_c diff --git a/tests/test_runner/test_parallel.py b/tests/test_runner/test_parallel.py index 08731f68eb..0b575a606a 100644 --- a/tests/test_runner/test_parallel.py +++ b/tests/test_runner/test_parallel.py @@ -15,7 +15,7 @@ class ExceptionThatFailsUnpickling(Exception): arguments passed to __init__(). """ def __init__(self, arg): - super(ExceptionThatFailsUnpickling, self).__init__() + super().__init__() class ParallelTestRunnerTest(SimpleTestCase): diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index ea094bbd55..19ef405852 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -799,7 +799,7 @@ class SkippingExtraTests(TestCase): def __call__(self, result=None): # Detect fixture loading by counting SQL queries, should be zero with self.assertNumQueries(0): - super(SkippingExtraTests, self).__call__(result) + super().__call__(result) @unittest.skip("Fixture loading should not be performed for skipped tests.") def test_fixtures_are_skipped(self): @@ -1017,7 +1017,7 @@ class TestBadSetUpTestData(TestCase): @classmethod def setUpClass(cls): try: - super(TestBadSetUpTestData, cls).setUpClass() + super().setUpClass() except cls.MyException: cls._in_atomic_block = connection.in_atomic_block diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py index e5a67f745e..586a2a3b47 100644 --- a/tests/timezones/tests.py +++ b/tests/timezones/tests.py @@ -596,7 +596,7 @@ class ForcedTimeZoneDatabaseTests(TransactionTestCase): if not connection.features.test_db_allows_multiple_connections: raise SkipTest("Database doesn't support feature(s): test_db_allows_multiple_connections") - super(ForcedTimeZoneDatabaseTests, cls).setUpClass() + super().setUpClass() @contextmanager def override_database_connection_timezone(self, timezone): diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py index 11bf163747..4a4e929cda 100644 --- a/tests/utils_tests/test_lazyobject.py +++ b/tests/utils_tests/test_lazyobject.py @@ -366,7 +366,7 @@ class BaseBaz: def __reduce__(self): self.baz = 'right' - return super(BaseBaz, self).__reduce__() + return super().__reduce__() def __eq__(self, other): if self.__class__ != other.__class__: @@ -385,11 +385,11 @@ class Baz(BaseBaz): """ def __init__(self, bar): self.bar = bar - super(Baz, self).__init__() + super().__init__() def __reduce_ex__(self, proto): self.quux = 'quux' - return super(Baz, self).__reduce_ex__(proto) + return super().__reduce_ex__(proto) class BazProxy(Baz): @@ -401,6 +401,7 @@ class BazProxy(Baz): def __init__(self, baz): self.__dict__ = baz.__dict__ self._baz = baz + # Grandparent super super(BaseBaz, self).__init__() diff --git a/tests/utils_tests/test_module_loading.py b/tests/utils_tests/test_module_loading.py index ad1135aa19..f66c167974 100644 --- a/tests/utils_tests/test_module_loading.py +++ b/tests/utils_tests/test_module_loading.py @@ -235,10 +235,10 @@ class CustomLoader(EggLoader): into one class, this isn't required. """ def setUp(self): - super(CustomLoader, self).setUp() + super().setUp() sys.path_hooks.insert(0, TestFinder) sys.path_importer_cache.clear() def tearDown(self): - super(CustomLoader, self).tearDown() + super().tearDown() sys.path_hooks.pop(0) diff --git a/tests/utils_tests/test_numberformat.py b/tests/utils_tests/test_numberformat.py index dd6057bb64..f78fc91087 100644 --- a/tests/utils_tests/test_numberformat.py +++ b/tests/utils_tests/test_numberformat.py @@ -64,7 +64,7 @@ class TestNumberFormat(TestCase): Wrapper for Decimal which prefixes each amount with the € symbol. """ def __format__(self, specifier, **kwargs): - amount = super(EuroDecimal, self).__format__(specifier, **kwargs) + amount = super().__format__(specifier, **kwargs) return '€ {}'.format(amount) price = EuroDecimal('1.23') diff --git a/tests/validation/models.py b/tests/validation/models.py index 043aa4ded7..f954cc3a4f 100644 --- a/tests/validation/models.py +++ b/tests/validation/models.py @@ -33,7 +33,7 @@ class ModelToValidate(models.Model): slug = models.SlugField(blank=True) def clean(self): - super(ModelToValidate, self).clean() + super().clean() if self.number == 11: raise ValidationError('Invalid number supplied!') diff --git a/tests/view_tests/tests/test_csrf.py b/tests/view_tests/tests/test_csrf.py index d0dd07b9e1..d5da576758 100644 --- a/tests/view_tests/tests/test_csrf.py +++ b/tests/view_tests/tests/test_csrf.py @@ -10,7 +10,7 @@ from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure class CsrfViewTests(SimpleTestCase): def setUp(self): - super(CsrfViewTests, self).setUp() + super().setUp() self.client = Client(enforce_csrf_checks=True) @override_settings( diff --git a/tests/view_tests/tests/test_static.py b/tests/view_tests/tests/test_static.py index f1a992789f..e2d22eb54c 100644 --- a/tests/view_tests/tests/test_static.py +++ b/tests/view_tests/tests/test_static.py @@ -116,12 +116,12 @@ class StaticHelperTest(StaticTests): Test case to make sure the static URL pattern helper works as expected """ def setUp(self): - super(StaticHelperTest, self).setUp() + super().setUp() self._old_views_urlpatterns = urls.urlpatterns[:] urls.urlpatterns += static('/media/', document_root=media_dir) def tearDown(self): - super(StaticHelperTest, self).tearDown() + super().tearDown() urls.urlpatterns = self._old_views_urlpatterns |