Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fixed #28858 -- Removed unnecessary "else" statements. #9498

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion django/apps/config.py
Expand Up @@ -71,7 +71,7 @@ def _path_from_module(self, module):
"The app module %r has multiple filesystem locations (%r); "
"you must configure this app with an AppConfig subclass "
"with a 'path' class attribute." % (module, paths))
elif not paths:
if not paths:
raise ImproperlyConfigured(
"The app module %r has no filesystem location, "
"you must configure this app with an AppConfig subclass "
Expand Down
2 changes: 1 addition & 1 deletion django/conf/urls/static.py
Expand Up @@ -19,7 +19,7 @@ def static(prefix, view=serve, **kwargs):
"""
if not prefix:
raise ImproperlyConfigured("Empty static prefix not permitted")
elif not settings.DEBUG or '://' in prefix:
if not settings.DEBUG or '://' in prefix:
# No-op if not in debug mode or a non-local prefix.
return []
return [
Expand Down
710 changes: 307 additions & 403 deletions django/contrib/admin/checks.py

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions django/contrib/admin/models.py
Expand Up @@ -68,14 +68,13 @@ def __repr__(self):
def __str__(self):
if self.is_addition():
return gettext('Added "%(object)s".') % {'object': self.object_repr}
elif self.is_change():
if self.is_change():
return gettext('Changed "%(object)s" - %(changes)s') % {
'object': self.object_repr,
'changes': self.get_change_message(),
}
elif self.is_deletion():
if self.is_deletion():
return gettext('Deleted "%(object)s."') % {'object': self.object_repr}

return gettext('LogEntry Object')

def is_addition(self):
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/admin/options.py
Expand Up @@ -936,9 +936,9 @@ def get_search_results(self, request, queryset, search_term):
def construct_search(field_name):
if field_name.startswith('^'):
return "%s__istartswith" % field_name[1:]
elif field_name.startswith('='):
if field_name.startswith('='):
return "%s__iexact" % field_name[1:]
elif field_name.startswith('@'):
if field_name.startswith('@'):
return "%s__search" % field_name[1:]
# Use field_name if it includes a lookup.
opts = queryset.model._meta
Expand Down
13 changes: 7 additions & 6 deletions django/contrib/admin/templatetags/admin_list.py
Expand Up @@ -31,13 +31,14 @@ def paginator_number(cl, i):
"""
if i == DOT:
return '... '
elif i == cl.page_num:
if i == cl.page_num:
return format_html('<span class="this-page">{}</span> ', i + 1)
else:
return format_html('<a href="{}"{}>{}</a> ',
cl.get_query_string({PAGE_VAR: i}),
mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
i + 1)
return format_html(
'<a href="{}"{}>{}</a> ',
cl.get_query_string({PAGE_VAR: i}),
mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
i + 1,
)


@register.inclusion_tag('admin/pagination.html')
Expand Down
33 changes: 15 additions & 18 deletions django/contrib/admin/utils.py
Expand Up @@ -393,41 +393,39 @@ def display_for_field(value, field, empty_value_display):
return dict(field.flatchoices).get(value, empty_value_display)
# NullBooleanField needs special-case null-handling, so it comes
# before the general null test.
elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
if isinstance(field, (models.BooleanField, models.NullBooleanField)):
return _boolean_icon(value)
elif value is None:
if value is None:
return empty_value_display
elif isinstance(field, models.DateTimeField):
if isinstance(field, models.DateTimeField):
return formats.localize(timezone.template_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
if isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.DecimalField):
if isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, (models.IntegerField, models.FloatField)):
if isinstance(field, (models.IntegerField, models.FloatField)):
return formats.number_format(value)
elif isinstance(field, models.FileField) and value:
if isinstance(field, models.FileField) and value:
return format_html('<a href="{}">{}</a>', value.url, value)
else:
return display_for_value(value, empty_value_display)
return display_for_value(value, empty_value_display)


def display_for_value(value, empty_value_display, boolean=False):
from django.contrib.admin.templatetags.admin_list import _boolean_icon

if boolean:
return _boolean_icon(value)
elif value is None:
if value is None:
return empty_value_display
elif isinstance(value, datetime.datetime):
if isinstance(value, datetime.datetime):
return formats.localize(timezone.template_localtime(value))
elif isinstance(value, (datetime.date, datetime.time)):
if isinstance(value, (datetime.date, datetime.time)):
return formats.localize(value)
elif isinstance(value, (int, decimal.Decimal, float)):
if isinstance(value, (int, decimal.Decimal, float)):
return formats.number_format(value)
elif isinstance(value, (list, tuple)):
if isinstance(value, (list, tuple)):
return ', '.join(str(v) for v in value)
else:
return str(value)
return str(value)


class NotRelationField(Exception):
Expand All @@ -437,8 +435,7 @@ class NotRelationField(Exception):
def get_model_from_relation(field):
if hasattr(field, 'get_path_info'):
return field.get_path_info()[-1].to_opts.model
else:
raise NotRelationField
raise NotRelationField


def reverse_field_path(model, path):
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/admindocs/views.py
Expand Up @@ -370,7 +370,7 @@ def get_return_data_type(func_name):
if func_name.startswith('get_'):
if func_name.endswith('_list'):
return 'List'
elif func_name.endswith('_count'):
if func_name.endswith('_count'):
return 'Integer'
return ''

Expand Down
3 changes: 1 addition & 2 deletions django/contrib/auth/forms.py
Expand Up @@ -202,8 +202,7 @@ def clean(self):
else:
self.confirm_login_allowed(self.user_cache)
raise self.get_invalid_login_error()
else:
self.confirm_login_allowed(self.user_cache)
self.confirm_login_allowed(self.user_cache)

return self.cleaned_data

Expand Down
20 changes: 9 additions & 11 deletions django/contrib/auth/hashers.py
Expand Up @@ -114,18 +114,16 @@ def get_hasher(algorithm='default'):
"""
if hasattr(algorithm, 'algorithm'):
return algorithm

elif algorithm == 'default':
if algorithm == 'default':
return get_hashers()[0]

else:
hashers = get_hashers_by_algorithm()
try:
return hashers[algorithm]
except KeyError:
raise ValueError("Unknown password hashing algorithm '%s'. "
"Did you specify it in the PASSWORD_HASHERS "
"setting?" % algorithm)
hashers = get_hashers_by_algorithm()
try:
return hashers[algorithm]
except KeyError:
raise ValueError(
"Unknown password hashing algorithm '%s'. Did you specify it in "
"the PASSWORD_HASHERS setting?" % algorithm
)


def identify_hasher(encoded):
Expand Down
12 changes: 5 additions & 7 deletions django/contrib/contenttypes/fields.py
Expand Up @@ -138,7 +138,7 @@ def _check_content_type_field(self):
id='contenttypes.E003',
)
]
elif field.remote_field.model != ContentType:
if field.remote_field.model != ContentType:
return [
checks.Error(
"'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % (
Expand All @@ -152,8 +152,7 @@ def _check_content_type_field(self):
id='contenttypes.E004',
)
]
else:
return []
return []

def get_cache_name(self):
return self.name
Expand All @@ -162,11 +161,10 @@ def get_content_type(self, obj=None, id=None, using=None):
if obj is not None:
return ContentType.objects.db_manager(obj._state.db).get_for_model(
obj, for_concrete_model=self.for_concrete_model)
elif id is not None:
if id is not None:
return ContentType.objects.db_manager(using).get_for_id(id)
else:
# This should never happen. I love comments like this, don't you?
raise Exception("Impossible arguments to GFK.get_content_type!")
# This should never happen.
raise Exception("Impossible arguments to GFK.get_content_type!")

def get_prefetch_queryset(self, instances, queryset=None):
if queryset is not None:
Expand Down
5 changes: 2 additions & 3 deletions django/contrib/gis/db/backends/base/models.py
Expand Up @@ -96,10 +96,9 @@ def units(self):
"Return a tuple of the units and the name."
if self.projected or self.local:
return (self.linear_units, self.linear_name)
elif self.geographic:
if self.geographic:
return (self.angular_units, self.angular_name)
else:
return (None, None)
return (None, None)

@classmethod
def get_units(cls, wkt):
Expand Down
14 changes: 6 additions & 8 deletions django/contrib/gis/db/backends/base/operations.py
Expand Up @@ -98,11 +98,10 @@ def transform_value(value, field):
self.spatial_function_name('Transform'),
self.from_text, value.srid, f.srid,
)
elif self.connection.features.has_spatialrefsys_table:
if self.connection.features.has_spatialrefsys_table:
return '%s(%%s,%s)' % (self.from_text, f.srid)
else:
# For backwards compatibility on MySQL (#27464).
return '%s(%%s)' % self.from_text
# For backwards compatibility on MySQL (#27464).
return '%s(%%s)' % self.from_text

def check_expression_support(self, expression):
if isinstance(expression, self.disallowed_aggregates):
Expand Down Expand Up @@ -145,10 +144,9 @@ def get_area_att_for_field(self, field):
if self.connection.features.supports_area_geodetic:
return 'sq_m'
raise NotImplementedError('Area on geodetic coordinate systems not supported.')
else:
units_name = field.units_name(self.connection)
if units_name:
return AreaMeasure.unit_attname(units_name)
units_name = field.units_name(self.connection)
if units_name:
return AreaMeasure.unit_attname(units_name)

def get_distance_att_for_field(self, field):
dist_att = None
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/db/models/lookups.py
Expand Up @@ -282,7 +282,7 @@ class DistanceLookupBase(GISLookup):
def process_rhs_params(self):
if not 1 <= len(self.rhs_params) <= 3:
raise ValueError("2, 3, or 4-element tuple required for '%s' lookup." % self.lookup_name)
elif len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid':
if len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid':
raise ValueError("For 4-element tuples the last argument must be the 'spheroid' directive.")

# Check if the second parameter is a band index.
Expand Down
16 changes: 7 additions & 9 deletions django/contrib/gis/gdal/envelope.py
Expand Up @@ -48,8 +48,7 @@ def __init__(self, *args):
# A tuple was passed in.
if len(args[0]) != 4:
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
else:
self._from_sequence(args[0])
self._from_sequence(args[0])
else:
raise TypeError('Incorrect type of argument: %s' % type(args[0]))
elif len(args) == 4:
Expand All @@ -73,11 +72,10 @@ def __eq__(self, other):
if isinstance(other, Envelope):
return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \
(self.max_x == other.max_x) and (self.max_y == other.max_y)
elif isinstance(other, tuple) and len(other) == 4:
if isinstance(other, tuple) and len(other) == 4:
return (self.min_x == other[0]) and (self.min_y == other[1]) and \
(self.max_x == other[2]) and (self.max_y == other[3])
else:
raise GDALException('Equivalence testing only works with other Envelopes.')
raise GDALException('Equivalence testing only works with other Envelopes.')

def __str__(self):
"Return a string representation of the tuple."
Expand All @@ -104,13 +102,13 @@ def expand_to_include(self, *args):
if len(args) == 1:
if isinstance(args[0], Envelope):
return self.expand_to_include(args[0].tuple)
elif hasattr(args[0], 'x') and hasattr(args[0], 'y'):
if hasattr(args[0], 'x') and hasattr(args[0], 'y'):
return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y)
elif isinstance(args[0], (tuple, list)):
if isinstance(args[0], (tuple, list)):
# A tuple was passed in.
if len(args[0]) == 2:
return self.expand_to_include((args[0][0], args[0][1], args[0][0], args[0][1]))
elif len(args[0]) == 4:
if len(args[0]) == 4:
(minx, miny, maxx, maxy) = args[0]
if minx < self._envelope.MinX:
self._envelope.MinX = minx
Expand All @@ -126,7 +124,7 @@ def expand_to_include(self, *args):
raise TypeError('Incorrect type of argument: %s' % type(args[0]))
elif len(args) == 2:
# An x and an y parameter were passed in
return self.expand_to_include((args[0], args[1], args[0], args[1]))
return self.expand_to_include((args[0], args[1], args[0], args[1]))
elif len(args) == 4:
# Individual parameters passed in.
return self.expand_to_include(args)
Expand Down
5 changes: 2 additions & 3 deletions django/contrib/gis/gdal/error.py
Expand Up @@ -54,8 +54,7 @@ def check_err(code, cpl=False):

if code == ERR_NONE:
return
elif code in err_dict:
if code in err_dict:
e, msg = err_dict[code]
raise e(msg)
else:
raise GDALException('Unknown error code: "%s"' % code)
raise GDALException('Unknown error code: "%s"' % code)
6 changes: 3 additions & 3 deletions django/contrib/gis/gdal/geometries.py
Expand Up @@ -541,7 +541,7 @@ def tuple(self):
"Return the tuple of this point."
if self.coord_dim == 2:
return (self.x, self.y)
elif self.coord_dim == 3:
if self.coord_dim == 3:
return (self.x, self.y, self.z)
coords = tuple

Expand All @@ -556,9 +556,9 @@ def __getitem__(self, index):
dim = self.coord_dim
if dim == 1:
return (x.value,)
elif dim == 2:
if dim == 2:
return (x.value, y.value)
elif dim == 3:
if dim == 3:
return (x.value, y.value, z.value)
else:
raise IndexError('Index out of range when accessing points of a line string: %s.' % index)
Expand Down
7 changes: 3 additions & 4 deletions django/contrib/gis/gdal/geomtype.py
Expand Up @@ -61,12 +61,11 @@ def __eq__(self, other):
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
elif isinstance(other, str):
if isinstance(other, str):
return self.name.lower() == other.lower()
elif isinstance(other, int):
if isinstance(other, int):
return self.num == other
else:
return False
return False

@property
def name(self):
Expand Down
10 changes: 4 additions & 6 deletions django/contrib/gis/gdal/srs.py
Expand Up @@ -82,8 +82,7 @@ def __init__(self, srs_input='', srs_type='user'):
# If the pointer is NULL, throw an exception.
if not srs:
raise SRSException('Could not create spatial reference from: %s' % srs_input)
else:
self.ptr = srs
self.ptr = srs

# Importing from either the user input string or an integer SRID.
if srs_type == 'user':
Expand Down Expand Up @@ -170,12 +169,11 @@ def name(self):
"Return the name of this Spatial Reference."
if self.projected:
return self.attr_value('PROJCS')
elif self.geographic:
if self.geographic:
return self.attr_value('GEOGCS')
elif self.local:
if self.local:
return self.attr_value('LOCAL_CS')
else:
return None
return None

@property
def srid(self):
Expand Down