Ticket #28858: no-else-after-return.patch

File no-else-after-return.patch, 147.4 KB (added by Дилян Палаузов, 7 years ago)
  • django/apps/config.py

    commit 4b037b92b6f98081de848d31f06f0b4f7045d403
    Author: Дилян Палаузов <Dilyan.Palauzov@db.com>
    Date:   Mon Nov 20 13:15:38 2017 +0100
    
        Remove 'else' after 'return' or 'raise'
    
    diff --git a/django/apps/config.py b/django/apps/config.py
    index 157fda7..f5f913b 100644
    a b class AppConfig:  
    7171                "The app module %r has multiple filesystem locations (%r); "
    7272                "you must configure this app with an AppConfig subclass "
    7373                "with a 'path' class attribute." % (module, paths))
    74         elif not paths:
     74        if not paths:
    7575            raise ImproperlyConfigured(
    7676                "The app module %r has no filesystem location, "
    7777                "you must configure this app with an AppConfig subclass "
  • django/conf/urls/static.py

    diff --git a/django/conf/urls/static.py b/django/conf/urls/static.py
    index 150f4ff..83ebda4 100644
    a b def static(prefix, view=serve, **kwargs):  
    1919    """
    2020    if not prefix:
    2121        raise ImproperlyConfigured("Empty static prefix not permitted")
    22     elif not settings.DEBUG or '://' in prefix:
     22    if not settings.DEBUG or '://' in prefix:
    2323        # No-op if not in debug mode or a non-local prefix.
    2424        return []
    2525    return [
  • django/contrib/admin/checks.py

    diff --git a/django/contrib/admin/checks.py b/django/contrib/admin/checks.py
    index c8e05bd..182d805 100644
    a b class BaseModelAdminChecks:  
    8787        """
    8888        if not isinstance(obj.autocomplete_fields, (list, tuple)):
    8989            return must_be('a list or tuple', option='autocomplete_fields', obj=obj, id='admin.E036')
    90         else:
    91             return list(chain.from_iterable([
    92                 self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index)
    93                 for index, field_name in enumerate(obj.autocomplete_fields)
    94             ]))
     90        return list(chain.from_iterable([
     91            self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index)
     92            for index, field_name in enumerate(obj.autocomplete_fields)
     93        ]))
    9594
    9695    def _check_autocomplete_fields_item(self, obj, model, field_name, label):
    9796        """
    class BaseModelAdminChecks:  
    122121                        id='admin.E039',
    123122                    )
    124123                ]
    125             elif not related_admin.search_fields:
     124            if not related_admin.search_fields:
    126125                return [
    127126                    checks.Error(
    128127                        '%s must define "search_fields", because it\'s '
    class BaseModelAdminChecks:  
    142141
    143142        if not isinstance(obj.raw_id_fields, (list, tuple)):
    144143            return must_be('a list or tuple', option='raw_id_fields', obj=obj, id='admin.E001')
    145         else:
    146             return list(chain.from_iterable(
    147                 self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index)
    148                 for index, field_name in enumerate(obj.raw_id_fields)
    149             ))
     144        return list(chain.from_iterable(
     145            self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index)
     146            for index, field_name in enumerate(obj.raw_id_fields)
     147        ))
    150148
    151149    def _check_raw_id_fields_item(self, obj, model, field_name, label):
    152150        """ Check an item of `raw_id_fields`, i.e. check that field named
    class BaseModelAdminChecks:  
    162160            if not field.many_to_many and not isinstance(field, models.ForeignKey):
    163161                return must_be('a foreign key or a many-to-many field',
    164162                               option=label, obj=obj, id='admin.E003')
    165             else:
    166                 return []
     163            return []
    167164
    168165    def _check_fields(self, obj):
    169166        """ Check that `fields` only refer to existing fields, doesn't contain
    class BaseModelAdminChecks:  
    172169
    173170        if obj.fields is None:
    174171            return []
    175         elif not isinstance(obj.fields, (list, tuple)):
     172        if not isinstance(obj.fields, (list, tuple)):
    176173            return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004')
    177         elif obj.fieldsets:
     174        if obj.fieldsets:
    178175            return [
    179176                checks.Error(
    180177                    "Both 'fieldsets' and 'fields' are specified.",
    class BaseModelAdminChecks:  
    203200
    204201        if obj.fieldsets is None:
    205202            return []
    206         elif not isinstance(obj.fieldsets, (list, tuple)):
     203        if not isinstance(obj.fieldsets, (list, tuple)):
    207204            return must_be('a list or tuple', option='fieldsets', obj=obj, id='admin.E007')
    208         else:
    209             return list(chain.from_iterable(
    210                 self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index)
    211                 for index, fieldset in enumerate(obj.fieldsets)
    212             ))
     205        return list(chain.from_iterable(
     206            self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index)
     207            for index, fieldset in enumerate(obj.fieldsets)
     208        ))
    213209
    214210    def _check_fieldsets_item(self, obj, model, fieldset, label):
    215211        """ Check an item of `fieldsets`, i.e. check that this is a pair of a
    class BaseModelAdminChecks:  
    217213
    218214        if not isinstance(fieldset, (list, tuple)):
    219215            return must_be('a list or tuple', option=label, obj=obj, id='admin.E008')
    220         elif len(fieldset) != 2:
     216        if len(fieldset) != 2:
    221217            return must_be('of length 2', option=label, obj=obj, id='admin.E009')
    222         elif not isinstance(fieldset[1], dict):
     218        if not isinstance(fieldset[1], dict):
    223219            return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010')
    224         elif 'fields' not in fieldset[1]:
     220        if 'fields' not in fieldset[1]:
    225221            return [
    226222                checks.Error(
    227223                    "The value of '%s[1]' must contain the key 'fields'." % label,
    class BaseModelAdminChecks:  
    229225                    id='admin.E011',
    230226                )
    231227            ]
    232         elif not isinstance(fieldset[1]['fields'], (list, tuple)):
     228        if not isinstance(fieldset[1]['fields'], (list, tuple)):
    233229            return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, id='admin.E008')
    234230
    235231        fields = flatten(fieldset[1]['fields'])
    class BaseModelAdminChecks:  
    256252                self._check_field_spec_item(obj, model, field_name, "%s[%d]" % (label, index))
    257253                for index, field_name in enumerate(fields)
    258254            ))
    259         else:
    260             return self._check_field_spec_item(obj, model, fields, label)
     255        return self._check_field_spec_item(obj, model, fields, label)
    261256
    262257    def _check_field_spec_item(self, obj, model, field_name, label):
    263258        if field_name in obj.readonly_fields:
    class BaseModelAdminChecks:  
    265260            # it's in readonly_fields, readonly_fields will handle the
    266261            # validation of such things.
    267262            return []
     263        try:
     264            field = model._meta.get_field(field_name)
     265        except FieldDoesNotExist:
     266            # If we can't find a field on the model that matches, it could
     267            # be an extra field on the form.
     268            return []
    268269        else:
    269             try:
    270                 field = model._meta.get_field(field_name)
    271             except FieldDoesNotExist:
    272                 # If we can't find a field on the model that matches, it could
    273                 # be an extra field on the form.
    274                 return []
    275             else:
    276                 if (isinstance(field, models.ManyToManyField) and
    277                         not field.remote_field.through._meta.auto_created):
    278                     return [
    279                         checks.Error(
    280                             "The value of '%s' cannot include the ManyToManyField '%s', "
    281                             "because that field manually specifies a relationship model."
    282                             % (label, field_name),
    283                             obj=obj.__class__,
    284                             id='admin.E013',
    285                         )
    286                     ]
    287                 else:
    288                     return []
     270            if (isinstance(field, models.ManyToManyField) and
     271                    not field.remote_field.through._meta.auto_created):
     272                return [
     273                    checks.Error(
     274                        "The value of '%s' cannot include the ManyToManyField '%s', "
     275                        "because that field manually specifies a relationship model."
     276                        % (label, field_name),
     277                        obj=obj.__class__,
     278                        id='admin.E013',
     279                    )
     280                ]
     281            return []
    289282
    290283    def _check_exclude(self, obj):
    291284        """ Check that exclude is a sequence without duplicates. """
    292285
    293286        if obj.exclude is None:  # default value is None
    294287            return []
    295         elif not isinstance(obj.exclude, (list, tuple)):
     288        if not isinstance(obj.exclude, (list, tuple)):
    296289            return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014')
    297         elif len(obj.exclude) > len(set(obj.exclude)):
     290        if len(obj.exclude) > len(set(obj.exclude)):
    298291            return [
    299292                checks.Error(
    300293                    "The value of 'exclude' contains duplicate field(s).",
    class BaseModelAdminChecks:  
    302295                    id='admin.E015',
    303296                )
    304297            ]
    305         else:
    306             return []
     298        return []
    307299
    308300    def _check_form(self, obj):
    309301        """ Check that form subclasses BaseModelForm. """
    310302        if not issubclass(obj.form, BaseModelForm):
    311303            return must_inherit_from(parent='BaseModelForm', option='form',
    312304                                     obj=obj, id='admin.E016')
    313         else:
    314             return []
     305        return []
    315306
    316307    def _check_filter_vertical(self, obj):
    317308        """ Check that filter_vertical is a sequence of field names. """
    318309        if not isinstance(obj.filter_vertical, (list, tuple)):
    319310            return must_be('a list or tuple', option='filter_vertical', obj=obj, id='admin.E017')
    320         else:
    321             return list(chain.from_iterable(
    322                 self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index)
    323                 for index, field_name in enumerate(obj.filter_vertical)
    324             ))
     311        return list(chain.from_iterable(
     312            self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index)
     313            for index, field_name in enumerate(obj.filter_vertical)
     314        ))
    325315
    326316    def _check_filter_horizontal(self, obj):
    327317        """ Check that filter_horizontal is a sequence of field names. """
    328318        if not isinstance(obj.filter_horizontal, (list, tuple)):
    329319            return must_be('a list or tuple', option='filter_horizontal', obj=obj, id='admin.E018')
    330         else:
    331             return list(chain.from_iterable(
    332                 self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index)
    333                 for index, field_name in enumerate(obj.filter_horizontal)
    334             ))
     320        return list(chain.from_iterable(
     321            self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index)
     322            for index, field_name in enumerate(obj.filter_horizontal)
     323        ))
    335324
    336325    def _check_filter_item(self, obj, model, field_name, label):
    337326        """ Check one item of `filter_vertical` or `filter_horizontal`, i.e.
    class BaseModelAdminChecks:  
    342331        except FieldDoesNotExist:
    343332            return refer_to_missing_field(field=field_name, option=label,
    344333                                          model=model, obj=obj, id='admin.E019')
    345         else:
    346             if not field.many_to_many:
    347                 return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020')
    348             else:
    349                 return []
     334        if not field.many_to_many:
     335            return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020')
     336        return []
    350337
    351338    def _check_radio_fields(self, obj):
    352339        """ Check that `radio_fields` is a dictionary. """
    353340        if not isinstance(obj.radio_fields, dict):
    354341            return must_be('a dictionary', option='radio_fields', obj=obj, id='admin.E021')
    355         else:
    356             return list(chain.from_iterable(
    357                 self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') +
    358                 self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name)
    359                 for field_name, val in obj.radio_fields.items()
    360             ))
     342        return list(chain.from_iterable(
     343            self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') +
     344            self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name)
     345            for field_name, val in obj.radio_fields.items()
     346        ))
    361347
    362348    def _check_radio_fields_key(self, obj, model, field_name, label):
    363349        """ Check that a key of `radio_fields` dictionary is name of existing
    class BaseModelAdminChecks:  
    380366                        id='admin.E023',
    381367                    )
    382368                ]
    383             else:
    384                 return []
     369            return []
    385370
    386371    def _check_radio_fields_value(self, obj, val, label):
    387372        """ Check type of a value of `radio_fields` dictionary. """
    class BaseModelAdminChecks:  
    396381                    id='admin.E024',
    397382                )
    398383            ]
    399         else:
    400             return []
     384        return []
    401385
    402386    def _check_view_on_site_url(self, obj):
    403387        if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool):
    class BaseModelAdminChecks:  
    408392                    id='admin.E025',
    409393                )
    410394            ]
    411         else:
    412             return []
     395        return []
    413396
    414397    def _check_prepopulated_fields(self, obj):
    415398        """ Check that `prepopulated_fields` is a dictionary containing allowed
    416399        field types. """
    417400        if not isinstance(obj.prepopulated_fields, dict):
    418401            return must_be('a dictionary', option='prepopulated_fields', obj=obj, id='admin.E026')
    419         else:
    420             return list(chain.from_iterable(
    421                 self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') +
    422                 self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name)
    423                 for field_name, val in obj.prepopulated_fields.items()
    424             ))
     402        return list(chain.from_iterable(
     403            self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') +
     404            self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name)
     405            for field_name, val in obj.prepopulated_fields.items()
     406        ))
    425407
    426408    def _check_prepopulated_fields_key(self, obj, model, field_name, label):
    427409        """ Check a key of `prepopulated_fields` dictionary, i.e. check that it
    class BaseModelAdminChecks:  
    443425                        id='admin.E028',
    444426                    )
    445427                ]
    446             else:
    447                 return []
     428            return []
    448429
    449430    def _check_prepopulated_fields_value(self, obj, model, val, label):
    450431        """ Check a value of `prepopulated_fields` dictionary, i.e. it's an
    class BaseModelAdminChecks:  
    452433
    453434        if not isinstance(val, (list, tuple)):
    454435            return must_be('a list or tuple', option=label, obj=obj, id='admin.E029')
    455         else:
    456             return list(chain.from_iterable(
    457                 self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index))
    458                 for index, subfield_name in enumerate(val)
    459             ))
     436        return list(chain.from_iterable(
     437            self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index))
     438            for index, subfield_name in enumerate(val)
     439        ))
    460440
    461441    def _check_prepopulated_fields_value_item(self, obj, model, field_name, label):
    462442        """ For `prepopulated_fields` equal to {"slug": ("title",)},
    class BaseModelAdminChecks:  
    475455        # ordering = None
    476456        if obj.ordering is None:  # The default value is None
    477457            return []
    478         elif not isinstance(obj.ordering, (list, tuple)):
     458        if not isinstance(obj.ordering, (list, tuple)):
    479459            return must_be('a list or tuple', option='ordering', obj=obj, id='admin.E031')
    480         else:
    481             return list(chain.from_iterable(
    482                 self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index)
    483                 for index, field_name in enumerate(obj.ordering)
    484             ))
     460        return list(chain.from_iterable(
     461            self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index)
     462            for index, field_name in enumerate(obj.ordering)
     463        ))
    485464
    486465    def _check_ordering_item(self, obj, model, field_name, label):
    487466        """ Check that `ordering` refers to existing fields. """
    class BaseModelAdminChecks:  
    496475                    id='admin.E032',
    497476                )
    498477            ]
    499         elif field_name == '?':
     478        if field_name == '?':
    500479            return []
    501         elif LOOKUP_SEP in field_name:
     480        if LOOKUP_SEP in field_name:
    502481            # Skip ordering in the format field1__field2 (FIXME: checking
    503482            # this format would be nice, but it's a little fiddly).
    504483            return []
     484        if field_name.startswith('-'):
     485            field_name = field_name[1:]
     486        if field_name == 'pk':
     487            return []
     488        try:
     489            model._meta.get_field(field_name)
     490        except FieldDoesNotExist:
     491            return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033')
    505492        else:
    506             if field_name.startswith('-'):
    507                 field_name = field_name[1:]
    508             if field_name == 'pk':
    509                 return []
    510             try:
    511                 model._meta.get_field(field_name)
    512             except FieldDoesNotExist:
    513                 return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033')
    514             else:
    515                 return []
     493            return []
    516494
    517495    def _check_readonly_fields(self, obj):
    518496        """ Check that readonly_fields refers to proper attribute or field. """
    519497
    520498        if obj.readonly_fields == ():
    521499            return []
    522         elif not isinstance(obj.readonly_fields, (list, tuple)):
     500        if not isinstance(obj.readonly_fields, (list, tuple)):
    523501            return must_be('a list or tuple', option='readonly_fields', obj=obj, id='admin.E034')
    524         else:
    525             return list(chain.from_iterable(
    526                 self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index)
    527                 for index, field_name in enumerate(obj.readonly_fields)
    528             ))
     502        return list(chain.from_iterable(
     503            self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index)
     504            for index, field_name in enumerate(obj.readonly_fields)
     505        ))
    529506
    530507    def _check_readonly_fields_item(self, obj, model, field_name, label):
    531508        if callable(field_name):
    532509            return []
    533         elif hasattr(obj, field_name):
     510        if hasattr(obj, field_name):
    534511            return []
    535         elif hasattr(model, field_name):
     512        if hasattr(model, field_name):
    536513            return []
     514        try:
     515            model._meta.get_field(field_name)
     516        except FieldDoesNotExist:
     517            return [
     518                checks.Error(
     519                    "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % (
     520                        label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
     521                    ),
     522                    obj=obj.__class__,
     523                    id='admin.E035',
     524                )
     525            ]
    537526        else:
    538             try:
    539                 model._meta.get_field(field_name)
    540             except FieldDoesNotExist:
    541                 return [
    542                     checks.Error(
    543                         "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % (
    544                             label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
    545                         ),
    546                         obj=obj.__class__,
    547                         id='admin.E035',
    548                     )
    549                 ]
    550             else:
    551                 return []
     527            return []
    552528
    553529
    554530class ModelAdminChecks(BaseModelAdminChecks):
    class ModelAdminChecks(BaseModelAdminChecks):  
    575551        if not isinstance(obj.save_as, bool):
    576552            return must_be('a boolean', option='save_as',
    577553                           obj=obj, id='admin.E101')
    578         else:
    579             return []
     554        return []
    580555
    581556    def _check_save_on_top(self, obj):
    582557        """ Check save_on_top is a boolean. """
    class ModelAdminChecks(BaseModelAdminChecks):  
    584559        if not isinstance(obj.save_on_top, bool):
    585560            return must_be('a boolean', option='save_on_top',
    586561                           obj=obj, id='admin.E102')
    587         else:
    588             return []
     562        return []
    589563
    590564    def _check_inlines(self, obj):
    591565        """ Check all inline model admin classes. """
    592566
    593567        if not isinstance(obj.inlines, (list, tuple)):
    594568            return must_be('a list or tuple', option='inlines', obj=obj, id='admin.E103')
    595         else:
    596             return list(chain.from_iterable(
    597                 self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index)
    598                 for index, item in enumerate(obj.inlines)
    599             ))
     569        return list(chain.from_iterable(
     570            self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index)
     571            for index, item in enumerate(obj.inlines)
     572        ))
    600573
    601574    def _check_inlines_item(self, obj, model, inline, label):
    602575        """ Check one inline model admin. """
    class ModelAdminChecks(BaseModelAdminChecks):  
    612585                    id='admin.E104',
    613586                )
    614587            ]
    615         elif not inline.model:
     588        if not inline.model:
    616589            return [
    617590                checks.Error(
    618591                    "'%s' must have a 'model' attribute." % inline_label,
    class ModelAdminChecks(BaseModelAdminChecks):  
    620593                    id='admin.E105',
    621594                )
    622595            ]
    623         elif not issubclass(inline.model, models.Model):
     596        if not issubclass(inline.model, models.Model):
    624597            return must_be('a Model', option='%s.model' % inline_label, obj=obj, id='admin.E106')
    625         else:
    626             return inline(model, obj.admin_site).check()
     598        return inline(model, obj.admin_site).check()
    627599
    628600    def _check_list_display(self, obj):
    629601        """ Check that list_display only contains fields or usable attributes.
    class ModelAdminChecks(BaseModelAdminChecks):  
    631603
    632604        if not isinstance(obj.list_display, (list, tuple)):
    633605            return must_be('a list or tuple', option='list_display', obj=obj, id='admin.E107')
    634         else:
    635             return list(chain.from_iterable(
    636                 self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index)
    637                 for index, item in enumerate(obj.list_display)
    638             ))
     606        return list(chain.from_iterable(
     607            self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index)
     608            for index, item in enumerate(obj.list_display)
     609        ))
    639610
    640611    def _check_list_display_item(self, obj, model, item, label):
    641612        if callable(item):
    642613            return []
    643         elif hasattr(obj, item):
     614        if hasattr(obj, item):
    644615            return []
    645         elif hasattr(model, item):
     616        if hasattr(model, item):
    646617            try:
    647618                field = model._meta.get_field(item)
    648619            except FieldDoesNotExist:
    class ModelAdminChecks(BaseModelAdminChecks):  
    657628                        )
    658629                    ]
    659630                return []
    660         else:
    661             return [
    662                 checks.Error(
    663                     "The value of '%s' refers to '%s', which is not a callable, "
    664                     "an attribute of '%s', or an attribute or method on '%s.%s'." % (
    665                         label, item, obj.__class__.__name__,
    666                         model._meta.app_label, model._meta.object_name,
    667                     ),
    668                     obj=obj.__class__,
    669                     id='admin.E108',
    670                 )
    671             ]
     631        return [
     632            checks.Error(
     633                "The value of '%s' refers to '%s', which is not a callable, "
     634                "an attribute of '%s', or an attribute or method on '%s.%s'." % (
     635                    label, item, obj.__class__.__name__,
     636                    model._meta.app_label, model._meta.object_name,
     637                ),
     638                obj=obj.__class__,
     639                id='admin.E108',
     640            )
     641        ]
    672642
    673643    def _check_list_display_links(self, obj):
    674644        """ Check that list_display_links is a unique subset of list_display.
    class ModelAdminChecks(BaseModelAdminChecks):  
    677647
    678648        if obj.list_display_links is None:
    679649            return []
    680         elif not isinstance(obj.list_display_links, (list, tuple)):
     650        if not isinstance(obj.list_display_links, (list, tuple)):
    681651            return must_be('a list, a tuple, or None', option='list_display_links', obj=obj, id='admin.E110')
    682652        # Check only if ModelAdmin.get_list_display() isn't overridden.
    683         elif obj.get_list_display.__func__ is ModelAdmin.get_list_display:
     653        if obj.get_list_display.__func__ is ModelAdmin.get_list_display:
    684654            return list(chain.from_iterable(
    685655                self._check_list_display_links_item(obj, field_name, "list_display_links[%d]" % index)
    686656                for index, field_name in enumerate(obj.list_display_links)
    class ModelAdminChecks(BaseModelAdminChecks):  
    698668                    id='admin.E111',
    699669                )
    700670            ]
    701         else:
    702             return []
     671        return []
    703672
    704673    def _check_list_filter(self, obj):
    705674        if not isinstance(obj.list_filter, (list, tuple)):
    706675            return must_be('a list or tuple', option='list_filter', obj=obj, id='admin.E112')
    707         else:
    708             return list(chain.from_iterable(
    709                 self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index)
    710                 for index, item in enumerate(obj.list_filter)
    711             ))
     676        return list(chain.from_iterable(
     677            self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index)
     678            for index, item in enumerate(obj.list_filter)
     679        ))
    712680
    713681    def _check_list_filter_item(self, obj, model, item, label):
    714682        """
    class ModelAdminChecks(BaseModelAdminChecks):  
    727695                return must_inherit_from(parent='ListFilter', option=label,
    728696                                         obj=obj, id='admin.E113')
    729697            # ...  but not a FieldListFilter.
    730             elif issubclass(item, FieldListFilter):
     698            if issubclass(item, FieldListFilter):
    731699                return [
    732700                    checks.Error(
    733701                        "The value of '%s' must not inherit from 'FieldListFilter'." % label,
    class ModelAdminChecks(BaseModelAdminChecks):  
    735703                        id='admin.E114',
    736704                    )
    737705                ]
    738             else:
    739                 return []
    740         elif isinstance(item, (tuple, list)):
     706            return []
     707        if isinstance(item, (tuple, list)):
    741708            # item is option #2
    742709            field, list_filter_class = item
    743710            if not issubclass(list_filter_class, FieldListFilter):
    744711                return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115')
    745             else:
    746                 return []
    747         else:
    748             # item is option #1
    749             field = item
     712            return []
     713        # item is option #1
     714        field = item
    750715
    751             # Validate the field string
    752             try:
    753                 get_fields_from_path(model, field)
    754             except (NotRelationField, FieldDoesNotExist):
    755                 return [
    756                     checks.Error(
    757                         "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field),
    758                         obj=obj.__class__,
    759                         id='admin.E116',
    760                     )
    761                 ]
    762             else:
    763                 return []
     716        # Validate the field string
     717        try:
     718            get_fields_from_path(model, field)
     719        except (NotRelationField, FieldDoesNotExist):
     720            return [
     721                checks.Error(
     722                    "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field),
     723                    obj=obj.__class__,
     724                    id='admin.E116',
     725                )
     726            ]
     727        else:
     728            return []
    764729
    765730    def _check_list_select_related(self, obj):
    766731        """ Check that list_select_related is a boolean, a list or a tuple. """
    767732
    768733        if not isinstance(obj.list_select_related, (bool, list, tuple)):
    769734            return must_be('a boolean, tuple or list', option='list_select_related', obj=obj, id='admin.E117')
    770         else:
    771             return []
     735        return []
    772736
    773737    def _check_list_per_page(self, obj):
    774738        """ Check that list_per_page is an integer. """
    775739
    776740        if not isinstance(obj.list_per_page, int):
    777741            return must_be('an integer', option='list_per_page', obj=obj, id='admin.E118')
    778         else:
    779             return []
     742        return []
    780743
    781744    def _check_list_max_show_all(self, obj):
    782745        """ Check that list_max_show_all is an integer. """
    783746
    784747        if not isinstance(obj.list_max_show_all, int):
    785748            return must_be('an integer', option='list_max_show_all', obj=obj, id='admin.E119')
    786         else:
    787             return []
     749        return []
    788750
    789751    def _check_list_editable(self, obj):
    790752        """ Check that list_editable is a sequence of editable fields from
    class ModelAdminChecks(BaseModelAdminChecks):  
    792754
    793755        if not isinstance(obj.list_editable, (list, tuple)):
    794756            return must_be('a list or tuple', option='list_editable', obj=obj, id='admin.E120')
    795         else:
    796             return list(chain.from_iterable(
    797                 self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index)
    798                 for index, item in enumerate(obj.list_editable)
    799             ))
     757        return list(chain.from_iterable(
     758            self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index)
     759            for index, item in enumerate(obj.list_editable)
     760        ))
    800761
    801762    def _check_list_editable_item(self, obj, model, field_name, label):
    802763        try:
    class ModelAdminChecks(BaseModelAdminChecks):  
    813774                        id='admin.E122',
    814775                    )
    815776                ]
    816             elif obj.list_display_links and field_name in obj.list_display_links:
     777            if obj.list_display_links and field_name in obj.list_display_links:
    817778                return [
    818779                    checks.Error(
    819780                        "The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name,
    class ModelAdminChecks(BaseModelAdminChecks):  
    823784                ]
    824785            # If list_display[0] is in list_editable, check that
    825786            # list_display_links is set. See #22792 and #26229 for use cases.
    826             elif (obj.list_display[0] == field_name and not obj.list_display_links and
     787            if (obj.list_display[0] == field_name and not obj.list_display_links and
    827788                    obj.list_display_links is not None):
    828789                return [
    829790                    checks.Error(
    class ModelAdminChecks(BaseModelAdminChecks):  
    835796                        id='admin.E124',
    836797                    )
    837798                ]
    838             elif not field.editable:
     799            if not field.editable:
    839800                return [
    840801                    checks.Error(
    841802                        "The value of '%s' refers to '%s', which is not editable through the admin." % (
    class ModelAdminChecks(BaseModelAdminChecks):  
    845806                        id='admin.E125',
    846807                    )
    847808                ]
    848             else:
    849                 return []
     809            return []
    850810
    851811    def _check_search_fields(self, obj):
    852812        """ Check search_fields is a sequence. """
    853813
    854814        if not isinstance(obj.search_fields, (list, tuple)):
    855815            return must_be('a list or tuple', option='search_fields', obj=obj, id='admin.E126')
    856         else:
    857             return []
     816        return []
    858817
    859818    def _check_date_hierarchy(self, obj):
    860819        """ Check that date_hierarchy refers to DateField or DateTimeField. """
    861820
    862821        if obj.date_hierarchy is None:
    863822            return []
     823        try:
     824            field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
     825        except (NotRelationField, FieldDoesNotExist):
     826            return [
     827                checks.Error(
     828                    "The value of 'date_hierarchy' refers to '%s', which "
     829                    "does not refer to a Field." % obj.date_hierarchy,
     830                    obj=obj.__class__,
     831                    id='admin.E127',
     832                )
     833            ]
    864834        else:
    865             try:
    866                 field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
    867             except (NotRelationField, FieldDoesNotExist):
    868                 return [
    869                     checks.Error(
    870                         "The value of 'date_hierarchy' refers to '%s', which "
    871                         "does not refer to a Field." % obj.date_hierarchy,
    872                         obj=obj.__class__,
    873                         id='admin.E127',
    874                     )
    875                 ]
    876             else:
    877                 if not isinstance(field, (models.DateField, models.DateTimeField)):
    878                     return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
    879                 else:
    880                     return []
     835            if not isinstance(field, (models.DateField, models.DateTimeField)):
     836                return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
     837            return []
    881838
    882839
    883840class InlineModelAdminChecks(BaseModelAdminChecks):
    class InlineModelAdminChecks(BaseModelAdminChecks):  
    919876                    id='admin.E201',
    920877                )
    921878            ]
    922         else:
    923             return []
     879        return []
    924880
    925881    def _check_relation(self, obj, parent_model):
    926882        try:
    class InlineModelAdminChecks(BaseModelAdminChecks):  
    935891
    936892        if not isinstance(obj.extra, int):
    937893            return must_be('an integer', option='extra', obj=obj, id='admin.E203')
    938         else:
    939             return []
     894        return []
    940895
    941896    def _check_max_num(self, obj):
    942897        """ Check that max_num is an integer. """
    943898
    944899        if obj.max_num is None:
    945900            return []
    946         elif not isinstance(obj.max_num, int):
     901        if not isinstance(obj.max_num, int):
    947902            return must_be('an integer', option='max_num', obj=obj, id='admin.E204')
    948         else:
    949             return []
     903        return []
    950904
    951905    def _check_min_num(self, obj):
    952906        """ Check that min_num is an integer. """
    953907
    954908        if obj.min_num is None:
    955909            return []
    956         elif not isinstance(obj.min_num, int):
     910        if not isinstance(obj.min_num, int):
    957911            return must_be('an integer', option='min_num', obj=obj, id='admin.E205')
    958         else:
    959             return []
     912        return []
    960913
    961914    def _check_formset(self, obj):
    962915        """ Check formset is a subclass of BaseModelFormSet. """
    963916
    964917        if not issubclass(obj.formset, BaseModelFormSet):
    965918            return must_inherit_from(parent='BaseModelFormSet', option='formset', obj=obj, id='admin.E206')
    966         else:
    967             return []
     919        return []
    968920
    969921
    970922def must_be(type, option, obj, id):
  • django/contrib/admin/models.py

    diff --git a/django/contrib/admin/models.py b/django/contrib/admin/models.py
    index 2f8ecc8..893060a 100644
    a b class LogEntry(models.Model):  
    6868    def __str__(self):
    6969        if self.is_addition():
    7070            return gettext('Added "%(object)s".') % {'object': self.object_repr}
    71         elif self.is_change():
     71        if self.is_change():
    7272            return gettext('Changed "%(object)s" - %(changes)s') % {
    7373                'object': self.object_repr,
    7474                'changes': self.get_change_message(),
    7575            }
    76         elif self.is_deletion():
     76        if self.is_deletion():
    7777            return gettext('Deleted "%(object)s."') % {'object': self.object_repr}
    7878
    7979        return gettext('LogEntry Object')
  • django/contrib/admin/options.py

    diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
    index 627c76b..5a79bb2 100644
    a b class ModelAdmin(BaseModelAdmin):  
    939939        def construct_search(field_name):
    940940            if field_name.startswith('^'):
    941941                return "%s__istartswith" % field_name[1:]
    942             elif field_name.startswith('='):
     942            if field_name.startswith('='):
    943943                return "%s__iexact" % field_name[1:]
    944             elif field_name.startswith('@'):
     944            if field_name.startswith('@'):
    945945                return "%s__search" % field_name[1:]
    946946            # Use field_name if it includes a lookup.
    947947            opts = queryset.model._meta
  • django/contrib/admin/templatetags/admin_list.py

    diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py
    index 75b117f..a82bd15 100644
    a b def paginator_number(cl, i):  
    3131    """
    3232    if i == DOT:
    3333        return '... '
    34     elif i == cl.page_num:
     34    if i == cl.page_num:
    3535        return format_html('<span class="this-page">{}</span> ', i + 1)
    36     else:
    37         return format_html('<a href="{}"{}>{}</a> ',
    38                            cl.get_query_string({PAGE_VAR: i}),
    39                            mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
    40                            i + 1)
     36    return format_html('<a href="{}"{}>{}</a> ',
     37                       cl.get_query_string({PAGE_VAR: i}),
     38                       mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
     39                       i + 1)
    4140
    4241
    4342@register.inclusion_tag('admin/pagination.html')
  • django/contrib/admin/utils.py

    diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
    index f1e2d4e..2165d5a 100644
    a b def display_for_field(value, field, empty_value_display):  
    393393        return dict(field.flatchoices).get(value, empty_value_display)
    394394    # NullBooleanField needs special-case null-handling, so it comes
    395395    # before the general null test.
    396     elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
     396    if isinstance(field, (models.BooleanField, models.NullBooleanField)):
    397397        return _boolean_icon(value)
    398     elif value is None:
     398    if value is None:
    399399        return empty_value_display
    400     elif isinstance(field, models.DateTimeField):
     400    if isinstance(field, models.DateTimeField):
    401401        return formats.localize(timezone.template_localtime(value))
    402     elif isinstance(field, (models.DateField, models.TimeField)):
     402    if isinstance(field, (models.DateField, models.TimeField)):
    403403        return formats.localize(value)
    404     elif isinstance(field, models.DecimalField):
     404    if isinstance(field, models.DecimalField):
    405405        return formats.number_format(value, field.decimal_places)
    406     elif isinstance(field, (models.IntegerField, models.FloatField)):
     406    if isinstance(field, (models.IntegerField, models.FloatField)):
    407407        return formats.number_format(value)
    408     elif isinstance(field, models.FileField) and value:
     408    if isinstance(field, models.FileField) and value:
    409409        return format_html('<a href="{}">{}</a>', value.url, value)
    410     else:
    411         return display_for_value(value, empty_value_display)
     410    return display_for_value(value, empty_value_display)
    412411
    413412
    414413def display_for_value(value, empty_value_display, boolean=False):
    def display_for_value(value, empty_value_display, boolean=False):  
    416415
    417416    if boolean:
    418417        return _boolean_icon(value)
    419     elif value is None:
     418    if value is None:
    420419        return empty_value_display
    421     elif isinstance(value, datetime.datetime):
     420    if isinstance(value, datetime.datetime):
    422421        return formats.localize(timezone.template_localtime(value))
    423     elif isinstance(value, (datetime.date, datetime.time)):
     422    if isinstance(value, (datetime.date, datetime.time)):
    424423        return formats.localize(value)
    425     elif isinstance(value, (int, decimal.Decimal, float)):
     424    if isinstance(value, (int, decimal.Decimal, float)):
    426425        return formats.number_format(value)
    427     elif isinstance(value, (list, tuple)):
     426    if isinstance(value, (list, tuple)):
    428427        return ', '.join(str(v) for v in value)
    429     else:
    430         return str(value)
     428    return str(value)
    431429
    432430
    433431class NotRelationField(Exception):
    class NotRelationField(Exception):  
    437435def get_model_from_relation(field):
    438436    if hasattr(field, 'get_path_info'):
    439437        return field.get_path_info()[-1].to_opts.model
    440     else:
    441         raise NotRelationField
     438    raise NotRelationField
    442439
    443440
    444441def reverse_field_path(model, path):
  • django/contrib/admindocs/views.py

    diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py
    index e45898c..504e7b4 100644
    a b def get_return_data_type(func_name):  
    372372    if func_name.startswith('get_'):
    373373        if func_name.endswith('_list'):
    374374            return 'List'
    375         elif func_name.endswith('_count'):
     375        if func_name.endswith('_count'):
    376376            return 'Integer'
    377377    return ''
    378378
  • django/contrib/auth/forms.py

    diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
    index 18fca67..982f973 100644
    a b class AuthenticationForm(forms.Form):  
    202202                else:
    203203                    self.confirm_login_allowed(self.user_cache)
    204204                raise self.get_invalid_login_error()
    205             else:
    206                 self.confirm_login_allowed(self.user_cache)
     205            self.confirm_login_allowed(self.user_cache)
    207206
    208207        return self.cleaned_data
    209208
  • django/contrib/auth/hashers.py

    diff --git a/django/contrib/auth/hashers.py b/django/contrib/auth/hashers.py
    index c14ece2..ac8d061 100644
    a b def get_hasher(algorithm='default'):  
    115115    if hasattr(algorithm, 'algorithm'):
    116116        return algorithm
    117117
    118     elif algorithm == 'default':
     118    if algorithm == 'default':
    119119        return get_hashers()[0]
    120120
    121     else:
    122         hashers = get_hashers_by_algorithm()
    123         try:
    124             return hashers[algorithm]
    125         except KeyError:
    126             raise ValueError("Unknown password hashing algorithm '%s'. "
    127                              "Did you specify it in the PASSWORD_HASHERS "
    128                              "setting?" % algorithm)
     121    hashers = get_hashers_by_algorithm()
     122    try:
     123        return hashers[algorithm]
     124    except KeyError:
     125        raise ValueError("Unknown password hashing algorithm '%s'. "
     126                         "Did you specify it in the PASSWORD_HASHERS "
     127                         "setting?" % algorithm)
    129128
    130129
    131130def identify_hasher(encoded):
  • django/contrib/contenttypes/fields.py

    diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py
    index 2227707..650bb12 100644
    a b class GenericForeignKey(FieldCacheMixin):  
    138138                        id='contenttypes.E003',
    139139                    )
    140140                ]
    141             elif field.remote_field.model != ContentType:
     141            if field.remote_field.model != ContentType:
    142142                return [
    143143                    checks.Error(
    144144                        "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % (
    class GenericForeignKey(FieldCacheMixin):  
    152152                        id='contenttypes.E004',
    153153                    )
    154154                ]
    155             else:
    156                 return []
     155            return []
    157156
    158157    def get_cache_name(self):
    159158        return self.name
    class GenericForeignKey(FieldCacheMixin):  
    162161        if obj is not None:
    163162            return ContentType.objects.db_manager(obj._state.db).get_for_model(
    164163                obj, for_concrete_model=self.for_concrete_model)
    165         elif id is not None:
     164        if id is not None:
    166165            return ContentType.objects.db_manager(using).get_for_id(id)
    167         else:
    168             # This should never happen. I love comments like this, don't you?
    169             raise Exception("Impossible arguments to GFK.get_content_type!")
     166        # This should never happen. I love comments like this, don't you?
     167        raise Exception("Impossible arguments to GFK.get_content_type!")
    170168
    171169    def get_prefetch_queryset(self, instances, queryset=None):
    172170        if queryset is not None:
  • django/contrib/gis/db/backends/base/models.py

    diff --git a/django/contrib/gis/db/backends/base/models.py b/django/contrib/gis/db/backends/base/models.py
    index c25c1cc..50ecd97 100644
    a b class SpatialRefSysMixin:  
    9696        "Return a tuple of the units and the name."
    9797        if self.projected or self.local:
    9898            return (self.linear_units, self.linear_name)
    99         elif self.geographic:
     99        if self.geographic:
    100100            return (self.angular_units, self.angular_name)
    101         else:
    102             return (None, None)
     101        return (None, None)
    103102
    104103    @classmethod
    105104    def get_units(cls, wkt):
  • django/contrib/gis/db/backends/base/operations.py

    diff --git a/django/contrib/gis/db/backends/base/operations.py b/django/contrib/gis/db/backends/base/operations.py
    index 1b786f7..3109f73 100644
    a b class BaseSpatialOperations:  
    9898                self.spatial_function_name('Transform'),
    9999                self.from_text, value.srid, f.srid,
    100100            )
    101         elif self.connection.features.has_spatialrefsys_table:
     101        if self.connection.features.has_spatialrefsys_table:
    102102            return '%s(%%s,%s)' % (self.from_text, f.srid)
    103         else:
    104             # For backwards compatibility on MySQL (#27464).
    105             return '%s(%%s)' % self.from_text
     103        # For backwards compatibility on MySQL (#27464).
     104        return '%s(%%s)' % self.from_text
    106105
    107106    def check_expression_support(self, expression):
    108107        if isinstance(expression, self.disallowed_aggregates):
    class BaseSpatialOperations:  
    145144            if self.connection.features.supports_area_geodetic:
    146145                return 'sq_m'
    147146            raise NotImplementedError('Area on geodetic coordinate systems not supported.')
    148         else:
    149             units_name = field.units_name(self.connection)
    150             if units_name:
    151                 return AreaMeasure.unit_attname(units_name)
     147        units_name = field.units_name(self.connection)
     148        if units_name:
     149            return AreaMeasure.unit_attname(units_name)
    152150
    153151    def get_distance_att_for_field(self, field):
    154152        dist_att = None
  • django/contrib/gis/db/models/lookups.py

    diff --git a/django/contrib/gis/db/models/lookups.py b/django/contrib/gis/db/models/lookups.py
    index d531856..e649a6b 100644
    a b class DistanceLookupBase(GISLookup):  
    283283    def process_rhs_params(self):
    284284        if not 1 <= len(self.rhs_params) <= 3:
    285285            raise ValueError("2, 3, or 4-element tuple required for '%s' lookup." % self.lookup_name)
    286         elif len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid':
     286        if len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid':
    287287            raise ValueError("For 4-element tuples the last argument must be the 'spheroid' directive.")
    288288
    289289        # Check if the second parameter is a band index.
  • django/contrib/gis/gdal/envelope.py

    diff --git a/django/contrib/gis/gdal/envelope.py b/django/contrib/gis/gdal/envelope.py
    index bbcc5d0..0d3e040 100644
    a b class Envelope:  
    4848                # A tuple was passed in.
    4949                if len(args[0]) != 4:
    5050                    raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
    51                 else:
    52                     self._from_sequence(args[0])
     51                self._from_sequence(args[0])
    5352            else:
    5453                raise TypeError('Incorrect type of argument: %s' % type(args[0]))
    5554        elif len(args) == 4:
    class Envelope:  
    7372        if isinstance(other, Envelope):
    7473            return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \
    7574                   (self.max_x == other.max_x) and (self.max_y == other.max_y)
    76         elif isinstance(other, tuple) and len(other) == 4:
     75        if isinstance(other, tuple) and len(other) == 4:
    7776            return (self.min_x == other[0]) and (self.min_y == other[1]) and \
    7877                   (self.max_x == other[2]) and (self.max_y == other[3])
    79         else:
    80             raise GDALException('Equivalence testing only works with other Envelopes.')
     78        raise GDALException('Equivalence testing only works with other Envelopes.')
    8179
    8280    def __str__(self):
    8381        "Return a string representation of the tuple."
    class Envelope:  
    104102        if len(args) == 1:
    105103            if isinstance(args[0], Envelope):
    106104                return self.expand_to_include(args[0].tuple)
    107             elif hasattr(args[0], 'x') and hasattr(args[0], 'y'):
     105            if hasattr(args[0], 'x') and hasattr(args[0], 'y'):
    108106                return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y)
    109             elif isinstance(args[0], (tuple, list)):
     107            if isinstance(args[0], (tuple, list)):
    110108                # A tuple was passed in.
    111109                if len(args[0]) == 2:
    112110                    return self.expand_to_include((args[0][0], args[0][1], args[0][0], args[0][1]))
    113                 elif len(args[0]) == 4:
     111                if len(args[0]) == 4:
    114112                    (minx, miny, maxx, maxy) = args[0]
    115113                    if minx < self._envelope.MinX:
    116114                        self._envelope.MinX = minx
    class Envelope:  
    126124                raise TypeError('Incorrect type of argument: %s' % type(args[0]))
    127125        elif len(args) == 2:
    128126            # An x and an y parameter were passed in
    129                 return self.expand_to_include((args[0], args[1], args[0], args[1]))
     127            return self.expand_to_include((args[0], args[1], args[0], args[1]))
    130128        elif len(args) == 4:
    131129            # Individual parameters passed in.
    132130            return self.expand_to_include(args)
  • django/contrib/gis/gdal/error.py

    diff --git a/django/contrib/gis/gdal/error.py b/django/contrib/gis/gdal/error.py
    index e394b60..353629a 100644
    a b def check_err(code, cpl=False):  
    5454
    5555    if code == ERR_NONE:
    5656        return
    57     elif code in err_dict:
     57    if code in err_dict:
    5858        e, msg = err_dict[code]
    5959        raise e(msg)
    60     else:
    61         raise GDALException('Unknown error code: "%s"' % code)
     60    raise GDALException('Unknown error code: "%s"' % code)
  • django/contrib/gis/gdal/geometries.py

    diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py
    index 42fbeec..3933f12 100644
    a b class Point(OGRGeometry):  
    541541        "Return the tuple of this point."
    542542        if self.coord_dim == 2:
    543543            return (self.x, self.y)
    544         elif self.coord_dim == 3:
     544        if self.coord_dim == 3:
    545545            return (self.x, self.y, self.z)
    546546    coords = tuple
    547547
    class LineString(OGRGeometry):  
    556556            dim = self.coord_dim
    557557            if dim == 1:
    558558                return (x.value,)
    559             elif dim == 2:
     559            if dim == 2:
    560560                return (x.value, y.value)
    561             elif dim == 3:
     561            if dim == 3:
    562562                return (x.value, y.value, z.value)
    563563        else:
    564564            raise IndexError('Index out of range when accessing points of a line string: %s.' % index)
  • django/contrib/gis/gdal/geomtype.py

    diff --git a/django/contrib/gis/gdal/geomtype.py b/django/contrib/gis/gdal/geomtype.py
    index 2c6798a..3062960 100644
    a b class OGRGeomType:  
    6161        """
    6262        if isinstance(other, OGRGeomType):
    6363            return self.num == other.num
    64         elif isinstance(other, str):
     64        if isinstance(other, str):
    6565            return self.name.lower() == other.lower()
    66         elif isinstance(other, int):
     66        if isinstance(other, int):
    6767            return self.num == other
    68         else:
    69             return False
     68        return False
    7069
    7170    @property
    7271    def name(self):
  • django/contrib/gis/gdal/srs.py

    diff --git a/django/contrib/gis/gdal/srs.py b/django/contrib/gis/gdal/srs.py
    index b2e0b09..86bf755 100644
    a b class SpatialReference(GDALBase):  
    8282        # If the pointer is NULL, throw an exception.
    8383        if not srs:
    8484            raise SRSException('Could not create spatial reference from: %s' % srs_input)
    85         else:
    86             self.ptr = srs
     85        self.ptr = srs
    8786
    8887        # Importing from either the user input string or an integer SRID.
    8988        if srs_type == 'user':
    class SpatialReference(GDALBase):  
    170169        "Return the name of this Spatial Reference."
    171170        if self.projected:
    172171            return self.attr_value('PROJCS')
    173         elif self.geographic:
     172        if self.geographic:
    174173            return self.attr_value('GEOGCS')
    175         elif self.local:
     174        if self.local:
    176175            return self.attr_value('LOCAL_CS')
    177         else:
    178             return None
     176        return None
    179177
    180178    @property
    181179    def srid(self):
  • django/contrib/gis/geoip2/base.py

    diff --git a/django/contrib/gis/geoip2/base.py b/django/contrib/gis/geoip2/base.py
    index b1035ac..620b542 100644
    a b class GeoIP2:  
    115115
    116116    @property
    117117    def _reader(self):
    118         if self._country:
    119             return self._country
    120         else:
    121             return self._city
     118        return self._country or self._city
    122119
    123120    @property
    124121    def _country_or_city(self):
    125122        if self._country:
    126123            return self._country.country
    127         else:
    128             return self._city.city
     124        return self._city.city
    129125
    130126    def __del__(self):
    131127        # Cleanup any GeoIP file handles lying around.
    class GeoIP2:  
    151147        # Extra checks for the existence of country and city databases.
    152148        if city_or_country and not (self._country or self._city):
    153149            raise GeoIP2Exception('Invalid GeoIP country and city data files.')
    154         elif country and not self._country:
     150        if country and not self._country:
    155151            raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file)
    156         elif city and not self._city:
     152        if city and not self._city:
    157153            raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file)
    158154
    159155        # Return the query string back to the caller. GeoIP2 only takes IP addresses.
  • django/contrib/gis/geos/mutable_list.py

    diff --git a/django/contrib/gis/geos/mutable_list.py b/django/contrib/gis/geos/mutable_list.py
    index 90fcc6d..43ff3a9 100644
    a b class ListMixin:  
    160160                return True
    161161            if c:
    162162                return c
    163             elif other[i] < self[i]:
     163            if other[i] < self[i]:
    164164                return False
    165165        return len(self) < olen
    166166
  • django/contrib/gis/geos/point.py

    diff --git a/django/contrib/gis/geos/point.py b/django/contrib/gis/geos/point.py
    index ccf5b9d..eaf7bb6 100644
    a b class Point(GEOSGeometry):  
    9191            return 0
    9292        if self.hasz:
    9393            return 3
    94         else:
    95             return 2
     94        return 2
    9695
    9796    def _get_single_external(self, index):
    9897        if index == 0:
    9998            return self.x
    100         elif index == 1:
     99        if index == 1:
    101100            return self.y
    102         elif index == 2:
     101        if index == 2:
    103102            return self.z
    104103
    105104    _get_single_internal = _get_single_external
  • django/contrib/gis/geos/prototypes/errcheck.py

    diff --git a/django/contrib/gis/geos/prototypes/errcheck.py b/django/contrib/gis/geos/prototypes/errcheck.py
    index 7d5f842..b2dac46 100644
    a b def check_predicate(result, func, cargs):  
    4545    "Error checking for unary/binary predicate functions."
    4646    if result == 1:
    4747        return True
    48     elif result == 0:
     48    if result == 0:
    4949        return False
    50     else:
    51         raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
     50    raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
    5251
    5352
    5453def check_sized_string(result, func, cargs):
  • django/contrib/gis/geos/prototypes/io.py

    diff --git a/django/contrib/gis/geos/prototypes/io.py b/django/contrib/gis/geos/prototypes/io.py
    index 97f49c2..a2c1772 100644
    a b class _WKBReader(IOBase):  
    147147        if isinstance(wkb, memoryview):
    148148            wkb_s = bytes(wkb)
    149149            return wkb_reader_read(self.ptr, wkb_s, len(wkb_s))
    150         elif isinstance(wkb, (bytes, str)):
     150        if isinstance(wkb, (bytes, str)):
    151151            return wkb_reader_read_hex(self.ptr, wkb, len(wkb))
    152         else:
    153             raise TypeError
     152        raise TypeError
    154153
    155154
    156155# ### WKB/WKT Writer Classes ###
  • django/contrib/gis/measure.py

    diff --git a/django/contrib/gis/measure.py b/django/contrib/gis/measure.py
    index 3bb23d9..1d0eb64 100644
    a b class MeasureBase:  
    209209        lower = unit_str.lower()
    210210        if unit_str in cls.UNITS:
    211211            return unit_str
    212         elif lower in cls.UNITS:
     212        if lower in cls.UNITS:
    213213            return lower
    214         elif lower in cls.LALIAS:
     214        if lower in cls.LALIAS:
    215215            return cls.LALIAS[lower]
    216         else:
    217             raise Exception('Could not find a unit keyword associated with "%s"' % unit_str)
     216        raise Exception('Could not find a unit keyword associated with "%s"' % unit_str)
    218217
    219218
    220219class Distance(MeasureBase):
    class Distance(MeasureBase):  
    300299                default_unit=AREA_PREFIX + self._default_unit,
    301300                **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)}
    302301            )
    303         elif isinstance(other, NUMERIC_TYPES):
     302        if isinstance(other, NUMERIC_TYPES):
    304303            return self.__class__(
    305304                default_unit=self._default_unit,
    306305                **{self.STANDARD_UNIT: (self.standard * other)}
    307306            )
    308         else:
    309             raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % {
    310                 "distance": pretty_name(self.__class__),
    311             })
     307        raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % {
     308            "distance": pretty_name(self.__class__),
     309        })
    312310
    313311
    314312class Area(MeasureBase):
  • django/contrib/gis/utils/layermapping.py

    diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py
    index e4baf56..5c6fcca 100644
    a b class LayerMapping:  
    154154        if fid_range:
    155155            if isinstance(fid_range, (tuple, list)):
    156156                return slice(*fid_range)
    157             elif isinstance(fid_range, slice):
     157            if isinstance(fid_range, slice):
    158158                return fid_range
    159             else:
    160                 raise TypeError
    161         else:
    162             return None
     159            raise TypeError
     160        return None
    163161
    164162    def check_layer(self):
    165163        """
  • django/contrib/gis/utils/ogrinspect.py

    diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py
    index 9a09160..d183e8e 100644
    a b def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non  
    144144    def process_kwarg(kwarg):
    145145        if isinstance(kwarg, (list, tuple)):
    146146            return [s.lower() for s in kwarg]
    147         elif kwarg:
     147        if kwarg:
    148148            return [s.lower() for s in ogr_fields]
    149         else:
    150             return []
     149        return []
    151150    null_fields = process_kwarg(null)
    152151    blank_fields = process_kwarg(blank)
    153152    decimal_fields = process_kwarg(decimal)
    def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non  
    161160            kwlist.append('blank=True')
    162161        if kwlist:
    163162            return ', ' + ', '.join(kwlist)
    164         else:
    165             return ''
     163        return ''
    166164
    167165    # For those wishing to disable the imports.
    168166    if imports:
  • django/contrib/humanize/templatetags/humanize.py

    diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py
    index fa644fd..844992e 100644
    a b def naturalday(value, arg=None):  
    173173    delta = value - today
    174174    if delta.days == 0:
    175175        return _('today')
    176     elif delta.days == 1:
     176    if delta.days == 1:
    177177        return _('tomorrow')
    178     elif delta.days == -1:
     178    if delta.days == -1:
    179179        return _('yesterday')
    180180    return defaultfilters.date(value, arg)
    181181
    def naturaltime(value):  
    198198            return pgettext(
    199199                'naturaltime', '%(delta)s ago'
    200200            ) % {'delta': defaultfilters.timesince(value, now)}
    201         elif delta.seconds == 0:
     201        if delta.seconds == 0:
    202202            return _('now')
    203         elif delta.seconds < 60:
     203        if delta.seconds < 60:
    204204            return ngettext(
    205205                # Translators: please keep a non-breaking space (U+00A0)
    206206                # between count and time unit.
    207207                'a second ago', '%(count)s seconds ago', delta.seconds
    208208            ) % {'count': delta.seconds}
    209         elif delta.seconds // 60 < 60:
     209        if delta.seconds // 60 < 60:
    210210            count = delta.seconds // 60
    211211            return ngettext(
    212212                # Translators: please keep a non-breaking space (U+00A0)
    213213                # between count and time unit.
    214214                'a minute ago', '%(count)s minutes ago', count
    215215            ) % {'count': count}
    216         else:
    217             count = delta.seconds // 60 // 60
    218             return ngettext(
    219                 # Translators: please keep a non-breaking space (U+00A0)
    220                 # between count and time unit.
    221                 'an hour ago', '%(count)s hours ago', count
    222             ) % {'count': count}
    223     else:
    224         delta = value - now
    225         if delta.days != 0:
    226             return pgettext(
    227                 'naturaltime', '%(delta)s from now'
    228             ) % {'delta': defaultfilters.timeuntil(value, now)}
    229         elif delta.seconds == 0:
    230             return _('now')
    231         elif delta.seconds < 60:
    232             return ngettext(
    233                 # Translators: please keep a non-breaking space (U+00A0)
    234                 # between count and time unit.
    235                 'a second from now', '%(count)s seconds from now', delta.seconds
    236             ) % {'count': delta.seconds}
    237         elif delta.seconds // 60 < 60:
    238             count = delta.seconds // 60
    239             return ngettext(
    240                 # Translators: please keep a non-breaking space (U+00A0)
    241                 # between count and time unit.
    242                 'a minute from now', '%(count)s minutes from now', count
    243             ) % {'count': count}
    244         else:
    245             count = delta.seconds // 60 // 60
    246             return ngettext(
    247                 # Translators: please keep a non-breaking space (U+00A0)
    248                 # between count and time unit.
    249                 'an hour from now', '%(count)s hours from now', count
    250             ) % {'count': count}
     216        count = delta.seconds // 60 // 60
     217        return ngettext(
     218            # Translators: please keep a non-breaking space (U+00A0)
     219            # between count and time unit.
     220            'an hour ago', '%(count)s hours ago', count
     221        ) % {'count': count}
     222    delta = value - now
     223    if delta.days != 0:
     224        return pgettext(
     225            'naturaltime', '%(delta)s from now'
     226        ) % {'delta': defaultfilters.timeuntil(value, now)}
     227    if delta.seconds == 0:
     228        return _('now')
     229    if delta.seconds < 60:
     230        return ngettext(
     231            # Translators: please keep a non-breaking space (U+00A0)
     232            # between count and time unit.
     233            'a second from now', '%(count)s seconds from now', delta.seconds
     234        ) % {'count': delta.seconds}
     235    if delta.seconds // 60 < 60:
     236        count = delta.seconds // 60
     237        return ngettext(
     238            # Translators: please keep a non-breaking space (U+00A0)
     239            # between count and time unit.
     240            'a minute from now', '%(count)s minutes from now', count
     241        ) % {'count': count}
     242    count = delta.seconds // 60 // 60
     243    return ngettext(
     244        # Translators: please keep a non-breaking space (U+00A0)
     245        # between count and time unit.
     246        'an hour from now', '%(count)s hours from now', count
     247    ) % {'count': count}
  • django/contrib/postgres/fields/ranges.py

    diff --git a/django/contrib/postgres/fields/ranges.py b/django/contrib/postgres/fields/ranges.py
    index 0bb914d..3f0f1fb 100644
    a b class RangeField(models.Field):  
    3838    def get_prep_value(self, value):
    3939        if value is None:
    4040            return None
    41         elif isinstance(value, Range):
     41        if isinstance(value, Range):
    4242            return value
    43         elif isinstance(value, (list, tuple)):
     43        if isinstance(value, (list, tuple)):
    4444            return self.range_type(value[0], value[1])
    4545        return value
    4646
  • django/contrib/postgres/forms/jsonb.py

    diff --git a/django/contrib/postgres/forms/jsonb.py b/django/contrib/postgres/forms/jsonb.py
    index bb681e0..6418f26 100644
    a b class JSONField(forms.CharField):  
    2525            return value
    2626        if value in self.empty_values:
    2727            return None
    28         elif isinstance(value, (list, dict, int, float, JSONString)):
     28        if isinstance(value, (list, dict, int, float, JSONString)):
    2929            return value
    3030        try:
    3131            converted = json.loads(value)
    class JSONField(forms.CharField):  
    3737            )
    3838        if isinstance(converted, str):
    3939            return JSONString(converted)
    40         else:
    41             return converted
     40        return converted
    4241
    4342    def bound_data(self, data, initial):
    4443        if self.disabled:
  • django/contrib/sessions/backends/base.py

    diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py
    index 64955b8..e644919 100644
    a b class SessionBase:  
    103103            # could produce ValueError if there is no ':'
    104104            hash, serialized = encoded_data.split(b':', 1)
    105105            expected_hash = self._hash(serialized)
    106             if not constant_time_compare(hash.decode(), expected_hash):
    107                 raise SuspiciousSession("Session data corrupted")
    108             else:
     106            if constant_time_compare(hash.decode(), expected_hash):
    109107                return self.serializer().loads(serialized)
     108            raise SuspiciousSession("Session data corrupted")
    110109        except Exception as e:
    111110            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
    112111            # these happen, just return an empty dictionary (an empty session).
  • django/contrib/sites/models.py

    diff --git a/django/contrib/sites/models.py b/django/contrib/sites/models.py
    index 19f52e4..f67167d 100644
    a b class SiteManager(models.Manager):  
    5858        if getattr(settings, 'SITE_ID', ''):
    5959            site_id = settings.SITE_ID
    6060            return self._get_site_by_id(site_id)
    61         elif request:
     61        if request:
    6262            return self._get_site_by_request(request)
    6363
    6464        raise ImproperlyConfigured(
  • django/core/checks/registry.py

    diff --git a/django/core/checks/registry.py b/django/core/checks/registry.py
    index c580c80..8c73965 100644
    a b class CheckRegistry:  
    5050
    5151        if callable(check):
    5252            return inner(check)
    53         else:
    54             if check:
    55                 tags += (check, )
    56             return inner
     53        if check:
     54            tags += (check, )
     55        return inner
    5756
    5857    def run_checks(self, app_configs=None, tags=None, include_deployment_checks=False):
    5958        """
  • django/core/checks/urls.py

    diff --git a/django/core/checks/urls.py b/django/core/checks/urls.py
    index e51ca3f..5cf566b 100644
    a b def check_resolver(resolver):  
    2121    check_method = getattr(resolver, 'check', None)
    2222    if check_method is not None:
    2323        return check_method()
    24     elif not hasattr(resolver, 'resolve'):
     24    if not hasattr(resolver, 'resolve'):
    2525        return get_warning_for_invalid_pattern(resolver)
    26     else:
    27         return []
     26    return []
    2827
    2928
    3029@register(Tags.urls)
  • django/core/management/base.py

    diff --git a/django/core/management/base.py b/django/core/management/base.py
    index 41b6b0f..a2b34b2 100644
    a b class BaseCommand:  
    408408        if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues):
    409409            msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer
    410410            raise SystemCheckError(msg)
    411         else:
    412             msg = header + body + footer
     411        msg = header + body + footer
    413412
    414413        if msg:
    415414            if visible_issue_count:
  • django/core/serializers/json.py

    diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
    index 5d35440..4a42d40 100644
    a b class DjangoJSONEncoder(json.JSONEncoder):  
    8787            if r.endswith('+00:00'):
    8888                r = r[:-6] + 'Z'
    8989            return r
    90         elif isinstance(o, datetime.date):
     90        if isinstance(o, datetime.date):
    9191            return o.isoformat()
    92         elif isinstance(o, datetime.time):
     92        if isinstance(o, datetime.time):
    9393            if is_aware(o):
    9494                raise ValueError("JSON can't represent timezone-aware times.")
    9595            r = o.isoformat()
    9696            if o.microsecond:
    9797                r = r[:12]
    9898            return r
    99         elif isinstance(o, datetime.timedelta):
     99        if isinstance(o, datetime.timedelta):
    100100            return duration_iso_string(o)
    101         elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
     101        if isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
    102102            return str(o)
    103         else:
    104             return super().default(o)
     103        return super().default(o)
  • django/db/backends/base/base.py

    diff --git a/django/db/backends/base/base.py b/django/db/backends/base/base.py
    index 53c3c30..a0a7eb6 100644
    a b class BaseDatabaseWrapper:  
    125125        """
    126126        if not settings.USE_TZ:
    127127            return None
    128         elif self.features.supports_timezones:
     128        if self.features.supports_timezones:
    129129            return None
    130         elif self.settings_dict['TIME_ZONE'] is None:
     130        if self.settings_dict['TIME_ZONE'] is None:
    131131            return timezone.utc
    132         else:
    133             return pytz.timezone(self.settings_dict['TIME_ZONE'])
     132        return pytz.timezone(self.settings_dict['TIME_ZONE'])
    134133
    135134    @cached_property
    136135    def timezone_name(self):
    class BaseDatabaseWrapper:  
    139138        """
    140139        if not settings.USE_TZ:
    141140            return settings.TIME_ZONE
    142         elif self.settings_dict['TIME_ZONE'] is None:
     141        if self.settings_dict['TIME_ZONE'] is None:
    143142            return 'UTC'
    144         else:
    145             return self.settings_dict['TIME_ZONE']
     143        return self.settings_dict['TIME_ZONE']
    146144
    147145    @property
    148146    def queries_logged(self):
    class BaseDatabaseWrapper:  
    204202                raise ImproperlyConfigured(
    205203                    "Connection '%s' cannot set TIME_ZONE because USE_TZ is "
    206204                    "False." % self.alias)
    207             elif self.features.supports_timezones:
     205            if self.features.supports_timezones:
    208206                raise ImproperlyConfigured(
    209207                    "Connection '%s' cannot set TIME_ZONE because its engine "
    210208                    "handles time zones conversions natively." % self.alias)
  • django/db/backends/base/operations.py

    diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py
    index 6291e00..5576a14 100644
    a b class BaseDatabaseOperations:  
    167167        """
    168168        if fields:
    169169            raise NotSupportedError('DISTINCT ON fields is not supported by this database backend')
    170         else:
    171             return 'DISTINCT'
     170        return 'DISTINCT'
    172171
    173172    def fetch_returned_insert_id(self, cursor):
    174173        """
    class BaseDatabaseOperations:  
    208207        offset = low_mark or 0
    209208        if high_mark is not None:
    210209            return (high_mark - offset), offset
    211         elif offset:
     210        if offset:
    212211            return self.connection.ops.no_limit_value(), offset
    213212        return None, offset
    214213
    class BaseDatabaseOperations:  
    473472        """
    474473        if isinstance(value, datetime.datetime):   # must be before date
    475474            return self.adapt_datetimefield_value(value)
    476         elif isinstance(value, datetime.date):
     475        if isinstance(value, datetime.date):
    477476            return self.adapt_datefield_value(value)
    478         elif isinstance(value, datetime.time):
     477        if isinstance(value, datetime.time):
    479478            return self.adapt_timefield_value(value)
    480         elif isinstance(value, decimal.Decimal):
     479        if isinstance(value, decimal.Decimal):
    481480            return self.adapt_decimalfield_value(value)
    482         else:
    483             return value
     481        return value
    484482
    485483    def adapt_datefield_value(self, value):
    486484        """
    class BaseDatabaseOperations:  
    629627        if isinstance(start, int):
    630628            if start < 0:
    631629                return '%d %s' % (abs(start), self.PRECEDING)
    632             elif start == 0:
     630            if start == 0:
    633631                return self.CURRENT_ROW
    634         elif start is None:
     632        if start is None:
    635633            return self.UNBOUNDED_PRECEDING
    636634        raise ValueError("start argument must be a negative integer, zero, or None, but got '%s'." % start)
    637635
    class BaseDatabaseOperations:  
    639637        if isinstance(end, int):
    640638            if end == 0:
    641639                return self.CURRENT_ROW
    642             elif end > 0:
     640            if end > 0:
    643641                return '%d %s' % (end, self.FOLLOWING)
    644         elif end is None:
     642        if end is None:
    645643            return self.UNBOUNDED_FOLLOWING
    646644        raise ValueError("end argument must be a positive integer, zero, or None, but got '%s'." % end)
    647645
  • django/db/backends/base/schema.py

    diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py
    index 35b82dc..12dd432 100644
    a b class BaseDatabaseSchemaEditor:  
    487487                "db_type (are you using a badly-written custom field?)" %
    488488                (old_field, new_field),
    489489            )
    490         elif old_type is None and new_type is None and (
     490        if old_type is None and new_type is None and (
    491491                old_field.remote_field.through and new_field.remote_field.through and
    492492                old_field.remote_field.through._meta.auto_created and
    493493                new_field.remote_field.through._meta.auto_created):
    494494            return self._alter_many_to_many(model, old_field, new_field, strict)
    495         elif old_type is None and new_type is None and (
     495        if old_type is None and new_type is None and (
    496496                old_field.remote_field.through and new_field.remote_field.through and
    497497                not old_field.remote_field.through._meta.auto_created and
    498498                not new_field.remote_field.through._meta.auto_created):
    499499            # Both sides have through models; this is a no-op.
    500500            return
    501         elif old_type is None or new_type is None:
     501        if old_type is None or new_type is None:
    502502            raise ValueError(
    503503                "Cannot alter field %s into %s - they are not compatible types "
    504504                "(you cannot alter to or from M2M fields, or add or remove "
  • django/db/backends/mysql/introspection.py

    diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py
    index 28dc47f..a945fa1 100644
    a b class DatabaseIntrospection(BaseDatabaseIntrospection):  
    4141        if 'auto_increment' in description.extra:
    4242            if field_type == 'IntegerField':
    4343                return 'AutoField'
    44             elif field_type == 'BigIntegerField':
     44            if field_type == 'BigIntegerField':
    4545                return 'BigAutoField'
    4646        if description.is_unsigned:
    4747            if field_type == 'IntegerField':
    4848                return 'PositiveIntegerField'
    49             elif field_type == 'SmallIntegerField':
     49            if field_type == 'SmallIntegerField':
    5050                return 'PositiveSmallIntegerField'
    5151        return field_type
    5252
  • django/db/backends/mysql/operations.py

    diff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py
    index 711f18d..bab9fa0 100644
    a b class DatabaseOperations(BaseDatabaseOperations):  
    4949        if lookup_type in fields:
    5050            format_str = fields[lookup_type]
    5151            return "CAST(DATE_FORMAT(%s, '%s') AS DATE)" % (field_name, format_str)
    52         elif lookup_type == 'quarter':
     52        if lookup_type == 'quarter':
    5353            return "MAKEDATE(YEAR(%s), 1) + INTERVAL QUARTER(%s) QUARTER - INTERVAL 1 QUARTER" % (
    5454                field_name, field_name
    5555            )
    56         else:
    57             return "DATE(%s)" % (field_name)
     56        return "DATE(%s)" % (field_name)
    5857
    5958    def _convert_field_to_tz(self, field_name, tzname):
    6059        if settings.USE_TZ:
    class DatabaseOperations(BaseDatabaseOperations):  
    204203            return 'POW(%s)' % ','.join(sub_expressions)
    205204        # Convert the result to a signed integer since MySQL's binary operators
    206205        # return an unsigned integer.
    207         elif connector in ('&', '|', '<<'):
     206        if connector in ('&', '|', '<<'):
    208207            return 'CONVERT(%s, SIGNED)' % connector.join(sub_expressions)
    209         elif connector == '>>':
     208        if connector == '>>':
    210209            lhs, rhs = sub_expressions
    211210            return 'FLOOR(%(lhs)s / POW(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs}
    212211        return super().combine_expression(connector, sub_expressions)
  • django/db/backends/oracle/introspection.py

    diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py
    index dbd54c2..9dc9aa8 100644
    a b class DatabaseIntrospection(BaseDatabaseIntrospection):  
    3434            if scale == 0:
    3535                if precision > 11:
    3636                    return 'BigAutoField' if description.is_autofield else 'BigIntegerField'
    37                 elif precision == 1:
     37                if precision == 1:
    3838                    return 'BooleanField'
    39                 elif description.is_autofield:
     39                if description.is_autofield:
    4040                    return 'AutoField'
    41                 else:
    42                     return 'IntegerField'
    43             elif scale == -127:
     41                return 'IntegerField'
     42            if scale == -127:
    4443                return 'FloatField'
    4544
    4645        return super().get_field_type(data_type, description)
  • django/db/backends/oracle/operations.py

    diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py
    index fa29a89..11955f8 100644
    a b END;  
    6262        if lookup_type == 'week_day':
    6363            # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday.
    6464            return "TO_CHAR(%s, 'D')" % field_name
    65         elif lookup_type == 'week':
     65        if lookup_type == 'week':
    6666            # IW = ISO week number
    6767            return "TO_CHAR(%s, 'IW')" % field_name
    68         elif lookup_type == 'quarter':
     68        if lookup_type == 'quarter':
    6969            return "TO_CHAR(%s, 'Q')" % field_name
    70         else:
    71             # https://docs.oracle.com/database/121/SQLRF/functions067.htm#SQLRF00639
    72             return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
     70        # https://docs.oracle.com/database/121/SQLRF/functions067.htm#SQLRF00639
     71        return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
    7372
    7473    def date_interval_sql(self, timedelta):
    7574        """
    END;  
    8180        # https://docs.oracle.com/database/121/SQLRF/functions271.htm#SQLRF52058
    8281        if lookup_type in ('year', 'month'):
    8382            return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper())
    84         elif lookup_type == 'quarter':
     83        if lookup_type == 'quarter':
    8584            return "TRUNC(%s, 'Q')" % field_name
    86         else:
    87             return "TRUNC(%s)" % field_name
     85        return "TRUNC(%s)" % field_name
    8886
    8987    # Oracle crashes with "ORA-03113: end-of-file on communication channel"
    9088    # if the time zone name is passed in parameter. Use interpolation instead.
    END;  
    505503        lhs, rhs = sub_expressions
    506504        if connector == '%%':
    507505            return 'MOD(%s)' % ','.join(sub_expressions)
    508         elif connector == '&':
     506        if connector == '&':
    509507            return 'BITAND(%s)' % ','.join(sub_expressions)
    510         elif connector == '|':
     508        if connector == '|':
    511509            return 'BITAND(-%(lhs)s-1,%(rhs)s)+%(lhs)s' % {'lhs': lhs, 'rhs': rhs}
    512         elif connector == '<<':
     510        if connector == '<<':
    513511            return '(%(lhs)s * POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs}
    514         elif connector == '>>':
     512        if connector == '>>':
    515513            return 'FLOOR(%(lhs)s / POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs}
    516         elif connector == '^':
     514        if connector == '^':
    517515            return 'POWER(%s)' % ','.join(sub_expressions)
    518516        return super().combine_expression(connector, sub_expressions)
    519517
  • django/db/backends/oracle/schema.py

    diff --git a/django/db/backends/oracle/schema.py b/django/db/backends/oracle/schema.py
    index 39c3b7e..5ab14fb 100644
    a b class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):  
    2020    def quote_value(self, value):
    2121        if isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
    2222            return "'%s'" % value
    23         elif isinstance(value, str):
     23        if isinstance(value, str):
    2424            return "'%s'" % value.replace("\'", "\'\'")
    25         elif isinstance(value, (bytes, bytearray, memoryview)):
     25        if isinstance(value, (bytes, bytearray, memoryview)):
    2626            return "'%s'" % value.hex()
    27         elif isinstance(value, bool):
     27        if isinstance(value, bool):
    2828            return "1" if value else "0"
    29         else:
    30             return str(value)
     29        return str(value)
    3130
    3231    def remove_field(self, model, field):
    3332        # If the column is an identity column, drop the identity before
  • django/db/backends/postgresql/introspection.py

    diff --git a/django/db/backends/postgresql/introspection.py b/django/db/backends/postgresql/introspection.py
    index 30f764f..08d9193 100644
    a b class DatabaseIntrospection(BaseDatabaseIntrospection):  
    4444        if description.default and 'nextval' in description.default:
    4545            if field_type == 'IntegerField':
    4646                return 'AutoField'
    47             elif field_type == 'BigIntegerField':
     47            if field_type == 'BigIntegerField':
    4848                return 'BigAutoField'
    4949        return field_type
    5050
  • django/db/backends/postgresql/schema.py

    diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py
    index f957cc3..6b33c14 100644
    a b class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):  
    5050                return None
    5151            if db_type.startswith('varchar'):
    5252                return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_varchar_index)
    53             elif db_type.startswith('text'):
     53            if db_type.startswith('text'):
    5454                return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_text_index)
    5555        return None
    5656
  • django/db/backends/sqlite3/base.py

    diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
    index 13f9a57..c227eb1 100644
    a b def _sqlite_date_extract(lookup_type, dt):  
    317317        return None
    318318    if lookup_type == 'week_day':
    319319        return (dt.isoweekday() % 7) + 1
    320     elif lookup_type == 'week':
     320    if lookup_type == 'week':
    321321        return dt.isocalendar()[1]
    322     elif lookup_type == 'quarter':
     322    if lookup_type == 'quarter':
    323323        return math.ceil(dt.month / 3)
    324     else:
    325         return getattr(dt, lookup_type)
     324    return getattr(dt, lookup_type)
    326325
    327326
    328327def _sqlite_date_trunc(lookup_type, dt):
    def _sqlite_date_trunc(lookup_type, dt):  
    332331        return None
    333332    if lookup_type == 'year':
    334333        return "%i-01-01" % dt.year
    335     elif lookup_type == 'quarter':
     334    if lookup_type == 'quarter':
    336335        month_in_quarter = dt.month - (dt.month - 1) % 3
    337336        return '%i-%02i-01' % (dt.year, month_in_quarter)
    338     elif lookup_type == 'month':
     337    if lookup_type == 'month':
    339338        return "%i-%02i-01" % (dt.year, dt.month)
    340     elif lookup_type == 'day':
     339    if lookup_type == 'day':
    341340        return "%i-%02i-%02i" % (dt.year, dt.month, dt.day)
    342341
    343342
    def _sqlite_time_trunc(lookup_type, dt):  
    348347        return None
    349348    if lookup_type == 'hour':
    350349        return "%02i:00:00" % dt.hour
    351     elif lookup_type == 'minute':
     350    if lookup_type == 'minute':
    352351        return "%02i:%02i:00" % (dt.hour, dt.minute)
    353     elif lookup_type == 'second':
     352    if lookup_type == 'second':
    354353        return "%02i:%02i:%02i" % (dt.hour, dt.minute, dt.second)
    355354
    356355
    def _sqlite_datetime_extract(lookup_type, dt, tzname):  
    386385        return None
    387386    if lookup_type == 'week_day':
    388387        return (dt.isoweekday() % 7) + 1
    389     elif lookup_type == 'week':
     388    if lookup_type == 'week':
    390389        return dt.isocalendar()[1]
    391     elif lookup_type == 'quarter':
     390    if lookup_type == 'quarter':
    392391        return math.ceil(dt.month / 3)
    393     else:
    394         return getattr(dt, lookup_type)
     392    return getattr(dt, lookup_type)
    395393
    396394
    397395def _sqlite_datetime_trunc(lookup_type, dt, tzname):
    def _sqlite_datetime_trunc(lookup_type, dt, tzname):  
    400398        return None
    401399    if lookup_type == 'year':
    402400        return "%i-01-01 00:00:00" % dt.year
    403     elif lookup_type == 'quarter':
     401    if lookup_type == 'quarter':
    404402        month_in_quarter = dt.month - (dt.month - 1) % 3
    405403        return '%i-%02i-01 00:00:00' % (dt.year, month_in_quarter)
    406     elif lookup_type == 'month':
     404    if lookup_type == 'month':
    407405        return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
    408     elif lookup_type == 'day':
     406    if lookup_type == 'day':
    409407        return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
    410     elif lookup_type == 'hour':
     408    if lookup_type == 'hour':
    411409        return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
    412     elif lookup_type == 'minute':
     410    if lookup_type == 'minute':
    413411        return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
    414     elif lookup_type == 'second':
     412    if lookup_type == 'second':
    415413        return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
    416414
    417415
  • django/db/backends/sqlite3/operations.py

    diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py
    index f363da0..21668ce 100644
    a b class DatabaseOperations(BaseDatabaseOperations):  
    2525        """
    2626        if len(fields) == 1:
    2727            return 500
    28         elif len(fields) > 1:
     28        if fields:
    2929            return self.connection.features.max_query_params // len(fields)
    30         else:
    31             return len(objs)
     30        return len(objs)
    3231
    3332    def check_expression_support(self, expression):
    3433        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
  • django/db/backends/sqlite3/schema.py

    diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py
    index 71f6c1c..1f9a164 100644
    a b class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):  
    3939        # Manual emulation of SQLite parameter quoting
    4040        if isinstance(value, bool):
    4141            return str(int(value))
    42         elif isinstance(value, (Decimal, float, int)):
     42        if isinstance(value, (Decimal, float, int)):
    4343            return str(value)
    44         elif isinstance(value, str):
     44        if isinstance(value, str):
    4545            return "'%s'" % value.replace("\'", "\'\'")
    46         elif value is None:
     46        if value is None:
    4747            return "NULL"
    48         elif isinstance(value, (bytes, bytearray, memoryview)):
     48        if isinstance(value, (bytes, bytearray, memoryview)):
    4949            # Bytes are only allowed for BLOB fields, encoded as string
    5050            # literals containing hexadecimal data and preceded by a single "X"
    5151            # character.
    5252            return "X'%s'" % value.hex()
    53         else:
    54             raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value)))
     53        raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value)))
    5554
    5655    def _remake_table(self, model, create_field=None, delete_field=None, alter_field=None):
    5756        """
  • django/db/backends/utils.py

    diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py
    index f4641e3..8ffc1a0 100644
    a b class CursorWrapper:  
    5858        with self.db.wrap_database_errors:
    5959            if params is None and kparams is None:
    6060                return self.cursor.callproc(procname)
    61             elif kparams is None:
     61            if kparams is None:
    6262                return self.cursor.callproc(procname, params)
    63             else:
    64                 params = params or ()
    65                 return self.cursor.callproc(procname, params, kparams)
     63            params = params or ()
     64            return self.cursor.callproc(procname, params, kparams)
    6665
    6766    def execute(self, sql, params=None):
    6867        return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  • django/db/migrations/autodetector.py

    diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
    index ece58b9..a7e5949 100644
    a b class MigrationAutodetector:  
    5555        """
    5656        if isinstance(obj, list):
    5757            return [self.deep_deconstruct(value) for value in obj]
    58         elif isinstance(obj, tuple):
     58        if isinstance(obj, tuple):
    5959            return tuple(self.deep_deconstruct(value) for value in obj)
    60         elif isinstance(obj, dict):
     60        if isinstance(obj, dict):
    6161            return {
    6262                key: self.deep_deconstruct(value)
    6363                for key, value in obj.items()
    6464            }
    65         elif isinstance(obj, functools.partial):
     65        if isinstance(obj, functools.partial):
    6666            return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords))
    67         elif isinstance(obj, COMPILED_REGEX_TYPE):
     67        if isinstance(obj, COMPILED_REGEX_TYPE):
    6868            return RegexObject(obj)
    69         elif isinstance(obj, type):
     69        if isinstance(obj, type):
    7070            # If this is a type that implements 'deconstruct' as an instance method,
    7171            # avoid treating this as being deconstructible itself - see #22951
    7272            return obj
    73         elif hasattr(obj, 'deconstruct'):
     73        if hasattr(obj, 'deconstruct'):
    7474            deconstructed = obj.deconstruct()
    7575            if isinstance(obj, models.Field):
    7676                # we have a field which also returns a name
    class MigrationAutodetector:  
    8484                    for key, value in kwargs.items()
    8585                },
    8686            )
    87         else:
    88             return obj
     87        return obj
    8988
    9089    def only_relation_agnostic_fields(self, fields):
    9190        """
    class MigrationAutodetector:  
    370369                operation.name_lower == dependency[1].lower()
    371370            )
    372371        # Created field
    373         elif dependency[2] is not None and dependency[3] is True:
     372        if dependency[2] is not None and dependency[3] is True:
    374373            return (
    375374                (
    376375                    isinstance(operation, operations.CreateModel) and
    class MigrationAutodetector:  
    384383                )
    385384            )
    386385        # Removed field
    387         elif dependency[2] is not None and dependency[3] is False:
     386        if dependency[2] is not None and dependency[3] is False:
    388387            return (
    389388                isinstance(operation, operations.RemoveField) and
    390389                operation.model_name_lower == dependency[1].lower() and
    391390                operation.name_lower == dependency[2].lower()
    392391            )
    393392        # Removed model
    394         elif dependency[2] is None and dependency[3] is False:
     393        if dependency[2] is None and dependency[3] is False:
    395394            return (
    396395                isinstance(operation, operations.DeleteModel) and
    397396                operation.name_lower == dependency[1].lower()
    398397            )
    399398        # Field being altered
    400         elif dependency[2] is not None and dependency[3] == "alter":
     399        if dependency[2] is not None and dependency[3] == "alter":
    401400            return (
    402401                isinstance(operation, operations.AlterField) and
    403402                operation.model_name_lower == dependency[1].lower() and
    404403                operation.name_lower == dependency[2].lower()
    405404            )
    406405        # order_with_respect_to being unset for a field
    407         elif dependency[2] is not None and dependency[3] == "order_wrt_unset":
     406        if dependency[2] is not None and dependency[3] == "order_wrt_unset":
    408407            return (
    409408                isinstance(operation, operations.AlterOrderWithRespectTo) and
    410409                operation.name_lower == dependency[1].lower() and
    411410                (operation.order_with_respect_to or "").lower() != dependency[2].lower()
    412411            )
    413412        # Field is removed and part of an index/unique_together
    414         elif dependency[2] is not None and dependency[3] == "foo_together_change":
     413        if dependency[2] is not None and dependency[3] == "foo_together_change":
    415414            return (
    416415                isinstance(operation, (operations.AlterUniqueTogether,
    417416                                       operations.AlterIndexTogether)) and
    418417                operation.name_lower == dependency[1].lower()
    419418            )
    420419        # Unknown dependency. Raise an error.
    421         else:
    422             raise ValueError("Can't handle dependency %r" % (dependency, ))
     420        raise ValueError("Can't handle dependency %r" % (dependency, ))
    423421
    424422    def add_operation(self, app_label, operation, dependencies=None, beginning=False):
    425423        # Dependencies are (app_label, model_name, field_name, create/delete as True/False)
    class MigrationAutodetector:  
    12131211        if len(ops) == 1:
    12141212            if isinstance(ops[0], operations.CreateModel):
    12151213                return ops[0].name_lower
    1216             elif isinstance(ops[0], operations.DeleteModel):
     1214            if isinstance(ops[0], operations.DeleteModel):
    12171215                return "delete_%s" % ops[0].name_lower
    1218             elif isinstance(ops[0], operations.AddField):
     1216            if isinstance(ops[0], operations.AddField):
    12191217                return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
    1220             elif isinstance(ops[0], operations.RemoveField):
     1218            if isinstance(ops[0], operations.RemoveField):
    12211219                return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
    12221220        elif len(ops) > 1:
    12231221            if all(isinstance(o, operations.CreateModel) for o in ops):
  • django/db/migrations/loader.py

    diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py
    index 8a1cf43..ae79777 100644
    a b class MigrationLoader:  
    133133            raise AmbiguityError(
    134134                "There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix)
    135135            )
    136         elif len(results) == 0:
     136        if len(results) == 0:
    137137            raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix))
    138         else:
    139             return self.disk_migrations[results[0]]
     138        return self.disk_migrations[results[0]]
    140139
    141140    def check_key(self, key, current_app):
    142141        if (key[1] != "__first__" and key[1] != "__latest__") or key in self.graph:
  • django/db/migrations/operations/base.py

    diff --git a/django/db/migrations/operations/base.py b/django/db/migrations/operations/base.py
    index 6ecbfac..c5b2e63 100644
    a b class Operation:  
    120120        """
    121121        if self.elidable:
    122122            return [operation]
    123         elif operation.elidable:
     123        if operation.elidable:
    124124            return [self]
    125125        return False
    126126
  • django/db/migrations/operations/fields.py

    diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py
    index b2c552c..8bcbd72 100644
    a b class AddField(FieldOperation):  
    103103                        field=operation.field,
    104104                    ),
    105105                ]
    106             elif isinstance(operation, RemoveField):
     106            if isinstance(operation, RemoveField):
    107107                return []
    108             elif isinstance(operation, RenameField):
     108            if isinstance(operation, RenameField):
    109109                return [
    110110                    AddField(
    111111                        model_name=self.model_name,
    class AlterField(FieldOperation):  
    221221    def reduce(self, operation, in_between, app_label=None):
    222222        if isinstance(operation, RemoveField) and self.is_same_field_operation(operation):
    223223            return [operation]
    224         elif isinstance(operation, RenameField) and self.is_same_field_operation(operation):
     224        if isinstance(operation, RenameField) and self.is_same_field_operation(operation):
    225225            return [
    226226                operation,
    227227                AlterField(
  • django/db/migrations/operations/models.py

    diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
    index a1ff594..d56c0a5 100644
    a b class CreateModel(ModelOperation):  
    128128        """
    129129        if isinstance(model, str):
    130130            return model.split(".", 1)
    131         else:
    132             return model._meta.app_label, model._meta.object_name
     131        return model._meta.app_label, model._meta.object_name
    133132
    134133    def reduce(self, operation, in_between, app_label=None):
    135134        if (isinstance(operation, DeleteModel) and
    136135                self.name_lower == operation.name_lower and
    137136                not self.options.get("proxy", False)):
    138137            return []
    139         elif isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower:
     138        if isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower:
    140139            return [
    141140                CreateModel(
    142141                    operation.new_name,
    class CreateModel(ModelOperation):  
    146145                    managers=self.managers,
    147146                ),
    148147            ]
    149         elif isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower:
     148        if isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower:
    150149            new_options = self.options.copy()
    151150            new_options.update(operation.options)
    152151            return [
    class CreateModel(ModelOperation):  
    158157                    managers=self.managers,
    159158                ),
    160159            ]
    161         elif isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower:
     160        if isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower:
    162161            if isinstance(operation, AddField):
    163162                # Don't allow optimizations of FKs through models they reference
    164163                if hasattr(operation.field, "remote_field") and operation.field.remote_field:
    class CreateModel(ModelOperation):  
    181180                        managers=self.managers,
    182181                    ),
    183182                ]
    184             elif isinstance(operation, AlterField):
     183            if isinstance(operation, AlterField):
    185184                return [
    186185                    CreateModel(
    187186                        self.name,
    class CreateModel(ModelOperation):  
    194193                        managers=self.managers,
    195194                    ),
    196195                ]
    197             elif isinstance(operation, RemoveField):
     196            if isinstance(operation, RemoveField):
    198197                return [
    199198                    CreateModel(
    200199                        self.name,
    class CreateModel(ModelOperation):  
    208207                        managers=self.managers,
    209208                    ),
    210209                ]
    211             elif isinstance(operation, RenameField):
     210            if isinstance(operation, RenameField):
    212211                return [
    213212                    CreateModel(
    214213                        self.name,
    class RenameModel(ModelOperation):  
    284283    def _get_model_tuple(self, remote_model, app_label, model_name):
    285284        if remote_model == RECURSIVE_RELATIONSHIP_CONSTANT:
    286285            return app_label, model_name.lower()
    287         elif '.' in remote_model:
     286        if '.' in remote_model:
    288287            return tuple(remote_model.lower().split('.'))
    289         else:
    290             return app_label, remote_model.lower()
     288        return app_label, remote_model.lower()
    291289
    292290    def state_forwards(self, app_label, state):
    293291        # Add a new model.
  • django/db/migrations/state.py

    diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py
    index 4dfa3dd..b734598 100644
    a b def _get_app_label_and_model_name(model, app_label=''):  
    2121    if isinstance(model, str):
    2222        split = model.split('.', 1)
    2323        return tuple(split) if len(split) == 2 else (app_label, split[0])
    24     else:
    25         return model._meta.app_label, model._meta.model_name
     24    return model._meta.app_label, model._meta.model_name
    2625
    2726
    2827def _get_related_models(m):
  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index 3f4d655..09e5b62 100644
    a b class Model(metaclass=ModelBase):  
    14341434                )
    14351435            ]
    14361436
    1437         elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together):
     1437        if any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together):
    14381438            return [
    14391439                checks.Error(
    14401440                    "All 'index_together' elements must be lists or tuples.",
    class Model(metaclass=ModelBase):  
    14431443                )
    14441444            ]
    14451445
    1446         else:
    1447             errors = []
    1448             for fields in cls._meta.index_together:
    1449                 errors.extend(cls._check_local_fields(fields, "index_together"))
    1450             return errors
     1446        errors = []
     1447        for fields in cls._meta.index_together:
     1448            errors.extend(cls._check_local_fields(fields, "index_together"))
     1449        return errors
    14511450
    14521451    @classmethod
    14531452    def _check_unique_together(cls):
    class Model(metaclass=ModelBase):  
    14611460                )
    14621461            ]
    14631462
    1464         elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together):
     1463        if any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together):
    14651464            return [
    14661465                checks.Error(
    14671466                    "All 'unique_together' elements must be lists or tuples.",
    class Model(metaclass=ModelBase):  
    14701469                )
    14711470            ]
    14721471
    1473         else:
    1474             errors = []
    1475             for fields in cls._meta.unique_together:
    1476                 errors.extend(cls._check_local_fields(fields, "unique_together"))
    1477             return errors
     1472        errors = []
     1473        for fields in cls._meta.unique_together:
     1474            errors.extend(cls._check_local_fields(fields, "unique_together"))
     1475        return errors
    14781476
    14791477    @classmethod
    14801478    def _check_local_fields(cls, fields, option):
  • django/db/models/expressions.py

    diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
    index 82db5c8..dadbce6 100644
    a b class BaseExpression:  
    307307        internal_type = field.get_internal_type()
    308308        if internal_type == 'FloatField':
    309309            return lambda value, expression, connection: None if value is None else float(value)
    310         elif internal_type.endswith('IntegerField'):
     310        if internal_type.endswith('IntegerField'):
    311311            return lambda value, expression, connection: None if value is None else int(value)
    312         elif internal_type == 'DecimalField':
     312        if internal_type == 'DecimalField':
    313313            return lambda value, expression, connection: None if value is None else Decimal(value)
    314314        return self._convert_value_noop
    315315
  • django/db/models/fields/__init__.py

    diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
    index 4a006bc..a40eb6a 100644
    a b class Field(RegisterLookupMixin):  
    222222                    id='fields.E001',
    223223                )
    224224            ]
    225         elif LOOKUP_SEP in self.name:
     225        if LOOKUP_SEP in self.name:
    226226            return [
    227227                checks.Error(
    228228                    'Field names must not contain "%s".' % (LOOKUP_SEP,),
    class Field(RegisterLookupMixin):  
    230230                    id='fields.E002',
    231231                )
    232232            ]
    233         elif self.name == 'pk':
     233        if self.name == 'pk':
    234234            return [
    235235                checks.Error(
    236236                    "'pk' is a reserved word that cannot be used as a field name.",
    class Field(RegisterLookupMixin):  
    238238                    id='fields.E003',
    239239                )
    240240            ]
    241         else:
    242             return []
     241        return []
    243242
    244243    def _check_choices(self):
    245244        if self.choices:
    class Field(RegisterLookupMixin):  
    251250                        id='fields.E004',
    252251                    )
    253252                ]
    254             elif any(isinstance(choice, str) or
     253            if any(isinstance(choice, str) or
    255254                     not is_iterable(choice) or len(choice) != 2
    256255                     for choice in self.choices):
    257256                return [
    class Field(RegisterLookupMixin):  
    262261                        id='fields.E005',
    263262                    )
    264263                ]
    265             else:
    266                 return []
    267         else:
    268             return []
     264        return []
    269265
    270266    def _check_db_index(self):
    271267        if self.db_index not in (None, True, False):
    class Field(RegisterLookupMixin):  
    276272                    id='fields.E006',
    277273                )
    278274            ]
    279         else:
    280             return []
     275        return []
    281276
    282277    def _check_null_allowed_for_primary_keys(self):
    283278        if (self.primary_key and self.null and
    class Field(RegisterLookupMixin):  
    294289                    id='fields.E007',
    295290                )
    296291            ]
    297         else:
    298             return []
     292        return []
    299293
    300294    def _check_backend_specific_checks(self, **kwargs):
    301295        app_label = self.model._meta.app_label
    class Field(RegisterLookupMixin):  
    337331                    id=self.system_check_removed_details.get('id', 'fields.EXXX'),
    338332                )
    339333            ]
    340         elif self.system_check_deprecated_details is not None:
     334        if self.system_check_deprecated_details is not None:
    341335            return [
    342336                checks.Warning(
    343337                    self.system_check_deprecated_details.get(
    class CharField(Field):  
    10511045                    id='fields.E120',
    10521046                )
    10531047            ]
    1054         elif (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or
     1048        if (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or
    10551049                self.max_length <= 0):
    10561050            return [
    10571051                checks.Error(
    class CharField(Field):  
    10601054                    id='fields.E121',
    10611055                )
    10621056            ]
    1063         else:
    1064             return []
     1057        return []
    10651058
    10661059    def cast_db_type(self, connection):
    10671060        if self.max_length is None:
    class DateTimeField(DateField):  
    13441337
    13451338    def to_python(self, value):
    13461339        if value is None:
    1347             return value
     1340            return None
    13481341        if isinstance(value, datetime.datetime):
    13491342            return value
    13501343        if isinstance(value, datetime.date):
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 34123fd..2ffbc67 100644
    a b class RelatedField(FieldCacheMixin, Field):  
    357357        base_q = Q(**base_filter)
    358358        if isinstance(descriptor_filter, dict):
    359359            return base_q & Q(**descriptor_filter)
    360         elif descriptor_filter:
     360        if descriptor_filter:
    361361            return base_q & descriptor_filter
    362362        return base_q
    363363
    class ForeignKey(ForeignObject):  
    832832                    id='fields.E320',
    833833                )
    834834            ]
    835         elif on_delete == SET_DEFAULT and not self.has_default():
     835        if on_delete == SET_DEFAULT and not self.has_default():
    836836            return [
    837837                checks.Error(
    838838                    'Field specifies on_delete=SET_DEFAULT, but has no default value.',
    class ForeignKey(ForeignObject):  
    841841                    id='fields.E321',
    842842                )
    843843            ]
    844         else:
    845             return []
     844        return []
    846845
    847846    def _check_unique(self, **kwargs):
    848847        return [
    class ManyToManyField(RelatedField):  
    15001499        """
    15011500        if self.remote_field.through is not None:
    15021501            return self.remote_field.through._meta.db_table
    1503         elif self.db_table:
     1502        if self.db_table:
    15041503            return self.db_table
    1505         else:
    1506             m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name)
    1507             return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
     1504        m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name)
     1505        return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
    15081506
    15091507    def _get_m2m_attr(self, related, attr):
    15101508        """
  • django/db/models/functions/datetime.py

    diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py
    index 44bcb73..ced659c 100644
    a b class TruncBase(TimezoneMixin, Transform):  
    198198            raise ValueError("Cannot truncate DateField '%s' to %s. " % (
    199199                field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField'
    200200            ))
    201         elif isinstance(field, TimeField) and (
     201        if isinstance(field, TimeField) and (
    202202                isinstance(output_field, DateTimeField) or copy.kind in ('year', 'quarter', 'month', 'day', 'date')):
    203203            raise ValueError("Cannot truncate TimeField '%s' to %s. " % (
    204204                field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField'
  • django/db/models/query.py

    diff --git a/django/db/models/query.py b/django/db/models/query.py
    index 39a8d3a..9261f73 100644
    a b class QuerySet:  
    11021102        """
    11031103        if self.query.extra_order_by or self.query.order_by:
    11041104            return True
    1105         elif self.query.default_ordering and self.query.get_meta().ordering:
     1105        if self.query.default_ordering and self.query.get_meta().ordering:
    11061106            return True
    1107         else:
    1108             return False
     1107        return False
    11091108
    11101109    @property
    11111110    def db(self):
  • django/db/models/query_utils.py

    diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py
    index 8a88926..2f29fa7 100644
    a b class Q(tree.Node):  
    6767        if not other:
    6868            return copy.deepcopy(self)
    6969        # Or if this Q is empty, ignore it and just use `other`.
    70         elif not self:
     70        if not self:
    7171            return copy.deepcopy(other)
    7272
    7373        obj = type(self)()
  • django/db/models/sql/compiler.py

    diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
    index 46559ff..0de137d 100644
    a b class SQLCompiler:  
    499499                    # possible deadlock.
    500500                    if nowait and not self.connection.features.has_select_for_update_nowait:
    501501                        raise NotSupportedError('NOWAIT is not supported on this database backend.')
    502                     elif skip_locked and not self.connection.features.has_select_for_update_skip_locked:
     502                    if skip_locked and not self.connection.features.has_select_for_update_skip_locked:
    503503                        raise NotSupportedError('SKIP LOCKED is not supported on this database backend.')
    504                     elif of and not self.connection.features.has_select_for_update_of:
     504                    if of and not self.connection.features.has_select_for_update_of:
    505505                        raise NotSupportedError('FOR UPDATE OF is not supported on this database backend.')
    506506                    for_update_part = self.connection.ops.for_update_sql(
    507507                        nowait=nowait,
    class SQLInsertCompiler(SQLCompiler):  
    11611161                raise FieldError("Aggregate functions are not allowed in this query")
    11621162            if value.contains_over_clause:
    11631163                raise FieldError('Window expressions are not allowed in this query.')
    1164         else:
    1165             value = field.get_db_prep_save(value, connection=self.connection)
    1166         return value
     1164            return value
     1165        return field.get_db_prep_save(value, connection=self.connection)
    11671166
    11681167    def pre_save_val(self, field, obj):
    11691168        """
  • django/db/models/sql/query.py

    diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
    index e7456de..1e26d25 100644
    a b class Query:  
    19401940        """
    19411941        if self._annotation_select_cache is not None:
    19421942            return self._annotation_select_cache
    1943         elif not self._annotations:
     1943        if not self._annotations:
    19441944            return {}
    1945         elif self.annotation_select_mask is not None:
     1945        if self.annotation_select_mask is not None:
    19461946            self._annotation_select_cache = OrderedDict(
    19471947                (k, v) for k, v in self.annotations.items()
    19481948                if k in self.annotation_select_mask
    19491949            )
    19501950            return self._annotation_select_cache
    1951         else:
    1952             return self.annotations
     1951        return self.annotations
    19531952
    19541953    @property
    19551954    def extra_select(self):
    class Query:  
    19571956            return self._extra_select_cache
    19581957        if not self._extra:
    19591958            return {}
    1960         elif self.extra_select_mask is not None:
     1959        if self.extra_select_mask is not None:
    19611960            self._extra_select_cache = OrderedDict(
    19621961                (k, v) for k, v in self.extra.items()
    19631962                if k in self.extra_select_mask
    19641963            )
    19651964            return self._extra_select_cache
    1966         else:
    1967             return self.extra
     1965        return self.extra
    19681966
    19691967    def trim_start(self, names_with_path):
    19701968        """
  • django/db/models/sql/where.py

    diff --git a/django/db/models/sql/where.py b/django/db/models/sql/where.py
    index 0ca95f7..137d2e5 100644
    a b class WhereNode(tree.Node):  
    9393            if empty_needed == 0:
    9494                if self.negated:
    9595                    return '', []
    96                 else:
    97                     raise EmptyResultSet
     96                raise EmptyResultSet
    9897            if full_needed == 0:
    9998                if self.negated:
    10099                    raise EmptyResultSet
    101                 else:
    102                     return '', []
     100                return '', []
    103101        conn = ' %s ' % self.connector
    104102        sql_string = conn.join(result)
    105103        if sql_string:
  • django/forms/boundfield.py

    diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py
    index dba54e5..93156ed 100644
    a b class BoundField:  
    193193        auto_id = self.form.auto_id  # Boolean or string
    194194        if auto_id and '%s' in str(auto_id):
    195195            return auto_id % self.html_name
    196         elif auto_id:
     196        if auto_id:
    197197            return self.html_name
    198198        return ''
    199199
  • django/forms/fields.py

    diff --git a/django/forms/fields.py b/django/forms/fields.py
    index 6412484..fa0bd75 100644
    a b class NullBooleanField(BooleanField):  
    739739        """
    740740        if value in (True, 'True', 'true', '1'):
    741741            return True
    742         elif value in (False, 'False', 'false', '0'):
     742        if value in (False, 'False', 'false', '0'):
    743743            return False
    744         else:
    745             return None
     744        return None
    746745
    747746    def validate(self, value):
    748747        pass
    class MultipleChoiceField(ChoiceField):  
    856855    def to_python(self, value):
    857856        if not value:
    858857            return []
    859         elif not isinstance(value, (list, tuple)):
     858        if not isinstance(value, (list, tuple)):
    860859            raise ValidationError(self.error_messages['invalid_list'], code='invalid_list')
    861860        return [str(val) for val in value]
    862861
    class MultiValueField(Field):  
    10051004            if not value or not [v for v in value if v not in self.empty_values]:
    10061005                if self.required:
    10071006                    raise ValidationError(self.error_messages['required'], code='required')
    1008                 else:
    1009                     return self.compress([])
     1007                return self.compress([])
    10101008        else:
    10111009            raise ValidationError(self.error_messages['invalid'], code='invalid')
    10121010        for i, field in enumerate(self.fields):
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 84a0c97..81ebd5f 100644
    a b class ModelMultipleChoiceField(ModelChoiceField):  
    12811281        value = self.prepare_value(value)
    12821282        if self.required and not value:
    12831283            raise ValidationError(self.error_messages['required'], code='required')
    1284         elif not self.required and not value:
     1284        if not self.required and not value:
    12851285            return self.queryset.none()
    12861286        if not isinstance(value, (list, tuple)):
    12871287            raise ValidationError(self.error_messages['list'], code='list')
  • django/middleware/csrf.py

    diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py
    index ce1329b..f5f43ba 100644
    a b def _sanitize_token(token):  
    106106    # Allow only ASCII alphanumerics
    107107    if re.search('[^a-zA-Z0-9]', token):
    108108        return _get_new_csrf_token()
    109     elif len(token) == CSRF_TOKEN_LENGTH:
     109    if len(token) == CSRF_TOKEN_LENGTH:
    110110        return token
    111     elif len(token) == CSRF_SECRET_LENGTH:
     111    if len(token) == CSRF_SECRET_LENGTH:
    112112        # Older Django versions set cookies to values of CSRF_SECRET_LENGTH
    113113        # alphanumeric characters. For backwards compatibility, accept
    114114        # such values as unsalted secrets.
  • django/template/base.py

    diff --git a/django/template/base.py b/django/template/base.py
    index 9c81a36..f5f6121 100644
    a b class Variable:  
    806806            msgid = mark_safe(msgid) if is_safe else msgid
    807807            if self.message_context:
    808808                return pgettext_lazy(self.message_context, msgid)
    809             else:
    810                 return gettext_lazy(msgid)
     809            return gettext_lazy(msgid)
    811810        return value
    812811
    813812    def __repr__(self):
  • django/template/defaulttags.py

    diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
    index 143082c..a872ffd 100644
    a b class IfChangedNode(Node):  
    241241            state_frame[self] = compare_to
    242242            # render true block if not already rendered
    243243            return nodelist_true_output or self.nodelist_true.render(context)
    244         elif self.nodelist_false:
     244        if self.nodelist_false:
    245245            return self.nodelist_false.render(context)
    246246        return ''
    247247
  • django/template/loader.py

    diff --git a/django/template/loader.py b/django/template/loader.py
    index 2492aee..245e6ba 100644
    a b def select_template(template_name_list, using=None):  
    4545
    4646    if template_name_list:
    4747        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    48     else:
    49         raise TemplateDoesNotExist("No template names provided")
     48    raise TemplateDoesNotExist("No template names provided")
    5049
    5150
    5251def render_to_string(template_name, context=None, request=None, using=None):
  • django/template/loaders/cached.py

    diff --git a/django/template/loaders/cached.py b/django/template/loaders/cached.py
    index b0799a2..8eb71bc 100644
    a b class Loader(BaseLoader):  
    4747        if cached:
    4848            if isinstance(cached, type) and issubclass(cached, TemplateDoesNotExist):
    4949                raise cached(template_name)
    50             elif isinstance(cached, TemplateDoesNotExist):
     50            if isinstance(cached, TemplateDoesNotExist):
    5151                raise copy_exception(cached)
    5252            return cached
    5353
    class Loader(BaseLoader):  
    5656        except TemplateDoesNotExist as e:
    5757            self.get_template_cache[key] = copy_exception(e) if self.engine.debug else TemplateDoesNotExist
    5858            raise
    59         else:
    60             self.get_template_cache[key] = template
     59        self.get_template_cache[key] = template
    6160
    6261        return template
    6362
  • django/template/response.py

    diff --git a/django/template/response.py b/django/template/response.py
    index 5631c78..ec1dd8a 100644
    a b class SimpleTemplateResponse(HttpResponse):  
    6161        """Accept a template object, path-to-template, or list of paths."""
    6262        if isinstance(template, (list, tuple)):
    6363            return select_template(template, using=self.using)
    64         elif isinstance(template, str):
     64        if isinstance(template, str):
    6565            return get_template(template, using=self.using)
    66         else:
    67             return template
     66        return template
    6867
    6968    def resolve_context(self, context):
    7069        return context
  • django/test/utils.py

    diff --git a/django/test/utils.py b/django/test/utils.py
    index fc783a4..5412a46 100644
    a b class ContextList(list):  
    6666                if key in subcontext:
    6767                    return subcontext[key]
    6868            raise KeyError(key)
    69         else:
    70             return super().__getitem__(key)
     69        return super().__getitem__(key)
    7170
    7271    def get(self, key, default=None):
    7372        try:
    class TestContextDecorator:  
    374373    def __call__(self, decorated):
    375374        if isinstance(decorated, type):
    376375            return self.decorate_class(decorated)
    377         elif callable(decorated):
     376        if callable(decorated):
    378377            return self.decorate_callable(decorated)
    379378        raise TypeError('Cannot decorate object of type %s' % type(decorated))
    380379
  • django/utils/archive.py

    diff --git a/django/utils/archive.py b/django/utils/archive.py
    index 879f3c4..fa984f6 100644
    a b class BaseArchive:  
    112112        path = path.lstrip('/').lstrip('\\')
    113113        if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path):
    114114            return path.split('/', 1)
    115         elif '\\' in path:
     115        if '\\' in path:
    116116            return path.split('\\', 1)
    117         else:
    118             return path, ''
     117        return path, ''
    119118
    120119    def has_leading_dir(self, paths):
    121120        """
    class BaseArchive:  
    127126            prefix, rest = self.split_leading_dir(path)
    128127            if not prefix:
    129128                return False
    130             elif common_prefix is None:
     129            if common_prefix is None:
    131130                common_prefix = prefix
    132131            elif prefix != common_prefix:
    133132                return False
  • django/utils/datastructures.py

    diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
    index 127c6dc7..973a1d7 100644
    a b class ImmutableList(tuple):  
    236236    def complain(self, *wargs, **kwargs):
    237237        if isinstance(self.warning, Exception):
    238238            raise self.warning
    239         else:
    240             raise AttributeError(self.warning)
     239        raise AttributeError(self.warning)
    241240
    242241    # All list mutation functions complain.
    243242    __delitem__ = complain
  • django/utils/formats.py

    diff --git a/django/utils/formats.py b/django/utils/formats.py
    index bba45e3..bec9fb1 100644
    a b def localize(value, use_l10n=None):  
    193193    """
    194194    if isinstance(value, str):  # Handle strings first for performance reasons.
    195195        return value
    196     elif isinstance(value, bool):  # Make sure booleans don't get treated as numbers
     196    if isinstance(value, bool):  # Make sure booleans don't get treated as numbers
    197197        return str(value)
    198     elif isinstance(value, (decimal.Decimal, float, int)):
     198    if isinstance(value, (decimal.Decimal, float, int)):
    199199        return number_format(value, use_l10n=use_l10n)
    200     elif isinstance(value, datetime.datetime):
     200    if isinstance(value, datetime.datetime):
    201201        return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
    202     elif isinstance(value, datetime.date):
     202    if isinstance(value, datetime.date):
    203203        return date_format(value, use_l10n=use_l10n)
    204     elif isinstance(value, datetime.time):
     204    if isinstance(value, datetime.time):
    205205        return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
    206206    return value
    207207
    def localize_input(value, default=None):  
    213213    """
    214214    if isinstance(value, str):  # Handle strings first for performance reasons.
    215215        return value
    216     elif isinstance(value, bool):  # Don't treat booleans as numbers.
     216    if isinstance(value, bool):  # Don't treat booleans as numbers.
    217217        return str(value)
    218     elif isinstance(value, (decimal.Decimal, float, int)):
     218    if isinstance(value, (decimal.Decimal, float, int)):
    219219        return number_format(value)
    220     elif isinstance(value, datetime.datetime):
     220    if isinstance(value, datetime.datetime):
    221221        value = datetime_safe.new_datetime(value)
    222222        format = default or get_format('DATETIME_INPUT_FORMATS')[0]
    223223        return value.strftime(format)
    224     elif isinstance(value, datetime.date):
     224    if isinstance(value, datetime.date):
    225225        value = datetime_safe.new_date(value)
    226226        format = default or get_format('DATE_INPUT_FORMATS')[0]
    227227        return value.strftime(format)
    228     elif isinstance(value, datetime.time):
     228    if isinstance(value, datetime.time):
    229229        format = default or get_format('TIME_INPUT_FORMATS')[0]
    230230        return value.strftime(format)
    231231    return value
  • django/utils/functional.py

    diff --git a/django/utils/functional.py b/django/utils/functional.py
    index af49322..ef7eed6 100644
    a b def lazy(func, *resultclasses):  
    121121        def __cast(self):
    122122            if self._delegate_bytes:
    123123                return self.__bytes_cast()
    124             elif self._delegate_text:
     124            if self._delegate_text:
    125125                return self.__text_cast()
    126             else:
    127                 return func(*self.__args, **self.__kw)
     126            return func(*self.__args, **self.__kw)
    128127
    129128        def __str__(self):
    130129            # object defines __str__(), so __prepare_class__() won't overload
  • django/utils/ipv6.py

    diff --git a/django/utils/ipv6.py b/django/utils/ipv6.py
    index ddb8c80..224c39c 100644
    a b def clean_ipv6_address(ip_str, unpack_ipv4=False,  
    2929
    3030    if unpack_ipv4 and addr.ipv4_mapped:
    3131        return str(addr.ipv4_mapped)
    32     elif addr.ipv4_mapped:
     32    if addr.ipv4_mapped:
    3333        return '::ffff:%s' % str(addr.ipv4_mapped)
    3434
    3535    return str(addr)
  • django/utils/safestring.py

    diff --git a/django/utils/safestring.py b/django/utils/safestring.py
    index 2da467a..b6fa2cf 100644
    a b class SafeBytes(bytes, SafeData):  
    3434        t = super().__add__(rhs)
    3535        if isinstance(rhs, SafeText):
    3636            return SafeText(t)
    37         elif isinstance(rhs, SafeBytes):
     37        if isinstance(rhs, SafeBytes):
    3838            return SafeBytes(t)
    3939        return t
    4040
  • django/views/generic/dates.py

    diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py
    index 2aedf3a..bcd5be5 100644
    a b class MonthMixin:  
    109109                return date.replace(year=date.year + 1, month=1, day=1)
    110110            except ValueError:
    111111                raise Http404(_("Date out of range"))
    112         else:
    113             return date.replace(month=date.month + 1, day=1)
     112        return date.replace(month=date.month + 1, day=1)
    114113
    115114    def _get_current_month(self, date):
    116115        """Return the start date of the previous interval."""
  • django/views/generic/detail.py

    diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py
    index 82599bd..17d91f4 100644
    a b class SingleObjectMixin(ContextMixin):  
    8282        """Get the name to use for the object."""
    8383        if self.context_object_name:
    8484            return self.context_object_name
    85         elif isinstance(obj, models.Model):
     85        if isinstance(obj, models.Model):
    8686            return obj._meta.model_name
    87         else:
    88             return None
     87        return None
    8988
    9089    def get_context_data(self, **kwargs):
    9190        """Insert the single object into the context dict."""
  • django/views/generic/list.py

    diff --git a/django/views/generic/list.py b/django/views/generic/list.py
    index 6753c1a..6fdcd81 100644
    a b class MultipleObjectMixin(ContextMixin):  
    105105        """Get the name of the item to be used in the context."""
    106106        if self.context_object_name:
    107107            return self.context_object_name
    108         elif hasattr(object_list, 'model'):
     108        if hasattr(object_list, 'model'):
    109109            return '%s_list' % object_list.model._meta.model_name
    110         else:
    111             return None
     110        return None
    112111
    113112    def get_context_data(self, *, object_list=None, **kwargs):
    114113        """Get the context for this view."""
  • scripts/manage_translations.py

    diff --git a/scripts/manage_translations.py b/scripts/manage_translations.py
    index 5397d35..8381568 100644
    a b def _tx_resource_for_name(name):  
    6363    """ Return the Transifex resource name """
    6464    if name == 'core':
    6565        return "django.core"
    66     else:
    67         return "django.contrib-%s" % name
     66    return "django.contrib-%s" % name
    6867
    6968
    7069def _check_diff(cat_name, base_path):
  • tests/admin_filters/tests.py

    diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py
    index 4a11c1a..6bdb0c8 100644
    a b class NotNinetiesListFilter(SimpleListFilter):  
    5151    def queryset(self, request, queryset):
    5252        if self.value() == 'the 90s':
    5353            return queryset.filter(year__gte=1990, year__lte=1999)
    54         else:
    55             return queryset.exclude(year__gte=1990, year__lte=1999)
     54        return queryset.exclude(year__gte=1990, year__lte=1999)
    5655
    5756
    5857class DecadeListFilterWithTitleAndParameter(DecadeListFilter):
    class DepartmentListFilterLookupWithDynamicValue(DecadeListFilterWithTitleAndPar  
    127126    def lookups(self, request, model_admin):
    128127        if self.value() == 'the 80s':
    129128            return (('the 90s', "the 1990's"),)
    130         elif self.value() == 'the 90s':
     129        if self.value() == 'the 90s':
    131130            return (('the 80s', "the 1980's"),)
    132         else:
    133             return (('the 80s', "the 1980's"), ('the 90s', "the 1990's"),)
     131        return (('the 80s', "the 1980's"), ('the 90s', "the 1990's"),)
    134132
    135133
    136134class CustomUserAdmin(UserAdmin):
  • tests/admin_ordering/models.py

    diff --git a/tests/admin_ordering/models.py b/tests/admin_ordering/models.py
    index b8098b9..3c091a0 100644
    a b class DynOrderingBandAdmin(admin.ModelAdmin):  
    3535    def get_ordering(self, request):
    3636        if request.user.is_superuser:
    3737            return ['rank']
    38         else:
    39             return ['name']
     38        return ['name']
  • tests/admin_views/admin.py

    diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py
    index 2c58bae..ffea097 100644
    a b class PostAdmin(admin.ModelAdmin):  
    450450    def coolness(self, instance):
    451451        if instance.pk:
    452452            return "%d amount of cool." % instance.pk
    453         else:
    454             return "Unknown coolness."
     453        return "Unknown coolness."
    455454
    456455    def value(self, instance):
    457456        return 1000
  • tests/auth_tests/test_auth_backends.py

    diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py
    index 86d5357..1c2d2c5 100644
    a b class SimpleRowlevelBackend:  
    332332        if isinstance(obj, TestObj):
    333333            if user.username == 'test2':
    334334                return True
    335             elif user.is_anonymous and perm == 'anon':
     335            if user.is_anonymous and perm == 'anon':
    336336                return True
    337             elif not user.is_active and perm == 'inactive':
     337            if not user.is_active and perm == 'inactive':
    338338                return True
    339339        return False
    340340
    class SimpleRowlevelBackend:  
    354354            return ['anon']
    355355        if user.username == 'test2':
    356356            return ['simple', 'advanced']
    357         else:
    358             return ['simple']
     357        return ['simple']
    359358
    360359    def get_group_permissions(self, user, obj=None):
    361360        if not obj:
    class SimpleRowlevelBackend:  
    366365
    367366        if 'test_group' in [group.name for group in user.groups.all()]:
    368367            return ['group_perm']
    369         else:
    370             return ['none']
     368        return ['none']
    371369
    372370
    373371@modify_settings(AUTHENTICATION_BACKENDS={
  • tests/builtin_server/tests.py

    diff --git a/tests/builtin_server/tests.py b/tests/builtin_server/tests.py
    index 73e3d0c..8c6ce80 100644
    a b class ServerHandler(simple_server.ServerHandler):  
    2020        if not self.status:
    2121            raise AssertionError("write() before start_response()")
    2222
    23         elif not self.headers_sent:
     23        if not self.headers_sent:
    2424            # Before the first output, send the stored headers
    2525            self.bytes_sent = len(data)    # make sure we know content-length
    2626            self.send_headers()
  • tests/contenttypes_tests/operations_migrations/0002_rename_foo.py

    diff --git a/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py b/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py
    index 3a1527d..62464ea 100644
    a b def assert_foo_contenttype_not_cached(apps, schema_editor):  
    1010    else:
    1111        if not ContentType.objects.filter(app_label='contenttypes_tests', model='foo').exists():
    1212            raise AssertionError('The contenttypes_tests.Foo ContentType should not be cached.')
    13         elif content_type.model != 'foo':
     13        if content_type.model != 'foo':
    1414            raise AssertionError(
    1515                "The cached contenttypes_tests.Foo ContentType should have "
    1616                "its model set to 'foo'."
  • tests/file_uploads/views.py

    diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py
    index 5c35a5a..c1cefbf 100644
    a b def file_upload_view(request):  
    2222        if os.path.dirname(form_data['file_field'].name) != '':
    2323            return HttpResponseServerError()
    2424        return HttpResponse('')
    25     else:
    26         return HttpResponseServerError()
     25    return HttpResponseServerError()
    2726
    2827
    2928def file_upload_view_verify(request):
    def file_upload_unicode_name(request):  
    7776    obj.delete()
    7877    os.unlink(full_name)
    7978
    80     if response:
    81         return response
    82     else:
    83         return HttpResponse('')
     79    return response or HttpResponse('')
    8480
    8581
    8682def file_upload_echo(request):
  • tests/forms_tests/field_tests/test_filepathfield.py

    diff --git a/tests/forms_tests/field_tests/test_filepathfield.py b/tests/forms_tests/field_tests/test_filepathfield.py
    index 44f6aff..dff1597 100644
    a b def fix_os_paths(x):  
    1111        if x.startswith(PATH):
    1212            x = x[len(PATH):]
    1313        return x.replace('\\', '/')
    14     elif isinstance(x, tuple):
     14    if isinstance(x, tuple):
    1515        return tuple(fix_os_paths(list(x)))
    16     elif isinstance(x, list):
     16    if isinstance(x, list):
    1717        return [fix_os_paths(y) for y in x]
    18     else:
    19         return x
     18    return x
    2019
    2120
    2221class FilePathFieldTest(SimpleTestCase):
  • tests/gis_tests/tests.py

    diff --git a/tests/gis_tests/tests.py b/tests/gis_tests/tests.py
    index 20b66cd..7e0a5dc 100644
    a b if HAS_POSTGRES:  
    2626            if func == 'postgis_lib_version':
    2727                if self.version is None:
    2828                    raise ProgrammingError
    29                 else:
    30                     return self.version
     29                return self.version
    3130            elif func == 'version':
    3231                pass
    3332            else:
  • tests/gis_tests/utils.py

    diff --git a/tests/gis_tests/utils.py b/tests/gis_tests/utils.py
    index b30da7e..ad44274 100644
    a b def no_backend(test_func, backend):  
    3131        def inner():
    3232            pass
    3333        return inner
    34     else:
    35         return test_func
     34    return test_func
    3635
    3736
    3837# Decorators to disable entire test functions for specific
  • tests/humanize_tests/tests.py

    diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py
    index df9ae4f..4a202ba 100644
    a b class HumanizeTests(SimpleTestCase):  
    277277            def now(cls, tz=None):
    278278                if tz is None or tz.utcoffset(documented_now) is None:
    279279                    return documented_now
    280                 else:
    281                     return documented_now.replace(tzinfo=tz) + tz.utcoffset(now)
     280                return documented_now.replace(tzinfo=tz) + tz.utcoffset(now)
    282281
    283282        orig_humanize_datetime = humanize.datetime
    284283        humanize.datetime = DocumentedMockDateTime
  • tests/i18n/test_extraction.py

    diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
    index fc8eaa2..b2fcfce 100644
    a b class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):  
    7979        pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE)
    8080        if assert_presence:
    8181            return self.assertRegex(po_contents, pattern, '"%s" not found in final .po file.' % needle)
    82         else:
    83             return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle)
     82        return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle)
    8483
    8584    def _get_token_line_number(self, path, token):
    8685        with open(path) as f:
  • tests/introspection/tests.py

    diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py
    index 63817a5..fb2f5c1 100644
    a b def datatype(dbtype, description):  
    211211    dt = connection.introspection.get_field_type(dbtype, description)
    212212    if type(dt) is tuple:
    213213        return dt[0]
    214     else:
    215         return dt
     214    return dt
  • tests/migrations/routers.py

    diff --git a/tests/migrations/routers.py b/tests/migrations/routers.py
    index 21dfc56..91c17c5 100644
    a b class TestRouter:  
    99        """
    1010        if model_name == 'tribble':
    1111            return db == 'other'
    12         elif db == 'other':
     12        if db == 'other':
    1313            return False
  • tests/migrations/test_commands.py

    diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py
    index 8caa0b5..46e720f 100644
    a b class MakeMigrationsTests(MigrationTestBase):  
    698698        def patched_has_table(migration_recorder):
    699699            if migration_recorder.connection is connections['other']:
    700700                raise Exception('Other connection')
    701             else:
    702                 return mock.DEFAULT
     701            return mock.DEFAULT
    703702
    704703        self.assertTableNotExists('migrations_unicodemodel')
    705704        apps.register_model('migrations', UnicodeModel)
  • tests/model_forms/models.py

    diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py
    index aecbeb1..74d6fa6 100644
    a b class CustomErrorMessage(models.Model):  
    377377    def clean(self):
    378378        if self.name1 == 'FORBIDDEN_VALUE':
    379379            raise ValidationError({'name1': [ValidationError('Model.clean() error messages.')]})
    380         elif self.name1 == 'FORBIDDEN_VALUE2':
     380        if self.name1 == 'FORBIDDEN_VALUE2':
    381381            raise ValidationError({'name1': 'Model.clean() error messages (simpler syntax).'})
    382         elif self.name1 == 'GLOBAL_ERROR':
     382        if self.name1 == 'GLOBAL_ERROR':
    383383            raise ValidationError("Global error message.")
    384384
    385385
  • tests/multiple_database/tests.py

    diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
    index 50859a3..c1cdb40 100644
    a b class AntiPetRouter:  
    15681568    def allow_migrate(self, db, app_label, model_name=None, **hints):
    15691569        if db == 'other':
    15701570            return model_name == 'pet'
    1571         else:
    1572             return model_name != 'pet'
     1571        return model_name != 'pet'
    15731572
    15741573
    15751574class FixtureTestCase(TestCase):
  • tests/runtests.py

    diff --git a/tests/runtests.py b/tests/runtests.py
    index ae2d693..f825357 100755
    a b def actual_test_processes(parallel):  
    236236        # This doesn't work before django.setup() on some databases.
    237237        if all(conn.features.can_clone_databases for conn in connections.all()):
    238238            return default_test_processes()
    239         else:
    240             return 1
    241     else:
    242         return parallel
     239        return 1
     240    return parallel
    243241
    244242
    245243class ActionSelenium(argparse.Action):
  • tests/servers/test_basehttp.py

    diff --git a/tests/servers/test_basehttp.py b/tests/servers/test_basehttp.py
    index 8372336..5ddc3ac 100644
    a b class WSGIRequestHandlerTestCase(SimpleTestCase):  
    101101        def makefile(mode, *a, **kw):
    102102            if mode == 'rb':
    103103                return rfile
    104             elif mode == 'wb':
     104            if mode == 'wb':
    105105                return wfile
    106106
    107107        request = Stub(makefile=makefile)
  • tests/template_tests/utils.py

    diff --git a/tests/template_tests/utils.py b/tests/template_tests/utils.py
    index 66a1733..b0cae08 100644
    a b class SomeClass:  
    115115    def __getitem__(self, key):
    116116        if key == 'silent_fail_key':
    117117            raise SomeException
    118         elif key == 'noisy_fail_key':
     118        if key == 'noisy_fail_key':
    119119            raise SomeOtherException
    120120        raise KeyError
    121121
  • tests/test_client/views.py

    diff --git a/tests/test_client/views.py b/tests/test_client/views.py
    index 3387008..bb6eb2e 100644
    a b def trace_view(request):  
    3333    """
    3434    if request.method.upper() != "TRACE":
    3535        return HttpResponseNotAllowed("TRACE")
    36     elif request.body:
     36    if request.body:
    3737        return HttpResponseBadRequest("TRACE requests MUST NOT include an entity")
    38     else:
    39         protocol = request.META["SERVER_PROTOCOL"]
    40         t = Template(
    41             '{{ method }} {{ uri }} {{ version }}',
    42             name="TRACE Template",
    43         )
    44         c = Context({
    45             'method': request.method,
    46             'uri': request.path,
    47             'version': protocol,
    48         })
    49         return HttpResponse(t.render(c))
     38    protocol = request.META["SERVER_PROTOCOL"]
     39    t = Template(
     40        '{{ method }} {{ uri }} {{ version }}',
     41        name="TRACE Template",
     42    )
     43    c = Context({
     44        'method': request.method,
     45        'uri': request.path,
     46        'version': protocol,
     47    })
     48    return HttpResponse(t.render(c))
    5049
    5150
    5251def post_view(request):
  • tests/test_client_regress/views.py

    diff --git a/tests/test_client_regress/views.py b/tests/test_client_regress/views.py
    index 5e4c996..e03f0e4 100644
    a b def view_with_argument(request, name):  
    5252    """
    5353    if name == 'Arthur Dent':
    5454        return HttpResponse('Hi, Arthur')
    55     else:
    56         return HttpResponse('Howdy, %s' % name)
     55    return HttpResponse('Howdy, %s' % name)
    5756
    5857
    5958def nested_view(request):
  • tests/utils_tests/test_lazyobject.py

    diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py
    index 2bba558..b6c8919 100644
    a b class BaseBaz:  
    376376        for attr in ['bar', 'baz', 'quux']:
    377377            if hasattr(self, attr) != hasattr(other, attr):
    378378                return False
    379             elif getattr(self, attr, None) != getattr(other, attr, None):
     379            if getattr(self, attr, None) != getattr(other, attr, None):
    380380                return False
    381381        return True
    382382
Back to Top