Fixed #28860 -- Removed unnecessary len() calls.

This commit is contained in:
Дилян Палаузов 2017-11-29 11:54:34 -05:00 committed by Tim Graham
parent 3d94ee8500
commit d2afa5eb23
33 changed files with 56 additions and 55 deletions

View File

@ -158,7 +158,7 @@ class AdminSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase):
# to be the case. # to be the case.
with self.disable_implicit_wait(): with self.disable_implicit_wait():
self.wait_until( self.wait_until(
lambda driver: len(driver.find_elements_by_css_selector(options_selector)) == 0 lambda driver: not driver.find_elements_by_css_selector(options_selector)
) )
def assertSelectOptions(self, selector, values): def assertSelectOptions(self, selector, values):

View File

@ -25,7 +25,7 @@ class GenericInlineModelAdminChecks(InlineModelAdminChecks):
f for f in obj.model._meta.private_fields f for f in obj.model._meta.private_fields
if isinstance(f, GenericForeignKey) if isinstance(f, GenericForeignKey)
] ]
if len(gfks) == 0: if not gfks:
return [ return [
checks.Error( checks.Error(
"'%s.%s' has no GenericForeignKey." % ( "'%s.%s' has no GenericForeignKey." % (

View File

@ -74,8 +74,7 @@ def get_flatpages(parser, token):
"['url_starts_with'] [for user] as context_name" % "['url_starts_with'] [for user] as context_name" %
{'tag_name': bits[0]}) {'tag_name': bits[0]})
# Must have at 3-6 bits in the tag # Must have at 3-6 bits in the tag
if len(bits) >= 3 and len(bits) <= 6: if 3 <= len(bits) <= 6:
# If there's an even number of bits, there's no prefix # If there's an even number of bits, there's no prefix
if len(bits) % 2 == 0: if len(bits) % 2 == 0:
prefix = bits[1] prefix = bits[1]

View File

@ -9,7 +9,7 @@ def City(response):
'latitude': response.location.latitude, 'latitude': response.location.latitude,
'longitude': response.location.longitude, 'longitude': response.location.longitude,
'postal_code': response.postal.code, 'postal_code': response.postal.code,
'region': response.subdivisions[0].iso_code if len(response.subdivisions) else None, 'region': response.subdivisions[0].iso_code if response.subdivisions else None,
'time_zone': response.location.time_zone, 'time_zone': response.location.time_zone,
} }

View File

@ -37,7 +37,7 @@ class Polygon(GEOSGeometry):
# If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility] # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility]
if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): if n_holes == 1 and isinstance(init_holes[0], (tuple, list)):
if len(init_holes[0]) == 0: if not init_holes[0]:
init_holes = () init_holes = ()
n_holes = 0 n_holes = 0
elif isinstance(init_holes[0][0], LinearRing): elif isinstance(init_holes[0][0], LinearRing):

View File

@ -351,7 +351,7 @@ class ManagementUtility:
if subcommand == 'help': if subcommand == 'help':
if '--commands' in args: if '--commands' in args:
sys.stdout.write(self.main_help_text(commands_only=True) + '\n') sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
elif len(options.args) < 1: elif not options.args:
sys.stdout.write(self.main_help_text() + '\n') sys.stdout.write(self.main_help_text() + '\n')
else: else:
self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0]) self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])

View File

@ -33,7 +33,7 @@ class Command(BaseCommand):
db = options['database'] db = options['database']
self.verbosity = options['verbosity'] self.verbosity = options['verbosity']
dry_run = options['dry_run'] dry_run = options['dry_run']
if len(tablenames): if tablenames:
# Legacy behavior, tablename specified as argument # Legacy behavior, tablename specified as argument
for tablename in tablenames: for tablename in tablenames:
self.create_table(db, tablename, dry_run) self.create_table(db, tablename, dry_run)

View File

@ -84,7 +84,7 @@ class Command(BaseCommand):
excluded_models, excluded_apps = parse_apps_and_model_labels(excludes) excluded_models, excluded_apps = parse_apps_and_model_labels(excludes)
if len(app_labels) == 0: if not app_labels:
if primary_keys: if primary_keys:
raise CommandError("You can only use --pks option with one model") raise CommandError("You can only use --pks option with one model")
app_list = OrderedDict.fromkeys( app_list = OrderedDict.fromkeys(

View File

@ -162,10 +162,11 @@ class Command(BaseCommand):
if not changes: if not changes:
# No changes? Tell them. # No changes? Tell them.
if self.verbosity >= 1: if self.verbosity >= 1:
if len(app_labels) == 1: if app_labels:
self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) if len(app_labels) == 1:
elif len(app_labels) > 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop())
self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else:
self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels)))
else: else:
self.stdout.write("No changes detected") self.stdout.write("No changes detected")
else: else:

View File

@ -476,7 +476,7 @@ class FormatStylePlaceholderCursor:
# Handle params as dict # Handle params as dict
args = {k: ":%s" % k for k in params} args = {k: ":%s" % k for k in params}
query = query % args query = query % args
elif unify_by_values and len(params) > 0: elif unify_by_values and params:
# Handle params as a dict with unified query parameters by their # Handle params as a dict with unified query parameters by their
# values. It can be used only in single query execute() because # values. It can be used only in single query execute() because
# executemany() shares the formatted query with each of the params # executemany() shares the formatted query with each of the params

View File

@ -132,7 +132,7 @@ class DatabaseOperations(BaseDatabaseOperations):
for sequence_info in sequences: for sequence_info in sequences:
table_name = sequence_info['table'] table_name = sequence_info['table']
column_name = sequence_info['column'] column_name = sequence_info['column']
if not (column_name and len(column_name) > 0): if not column_name:
# This will be the case if it's an m2m using an autogenerated # This will be the case if it's an m2m using an autogenerated
# intermediate table (see BaseDatabaseIntrospection.sequence_list) # intermediate table (see BaseDatabaseIntrospection.sequence_list)
column_name = 'id' column_name = 'id'

View File

@ -1219,7 +1219,7 @@ class MigrationAutodetector:
return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
elif isinstance(ops[0], operations.RemoveField): elif isinstance(ops[0], operations.RemoveField):
return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
elif len(ops) > 1: elif ops:
if all(isinstance(o, operations.CreateModel) for o in ops): if all(isinstance(o, operations.CreateModel) for o in ops):
return "_".join(sorted(o.name_lower for o in ops)) return "_".join(sorted(o.name_lower for o in ops))
return "auto_%s" % get_migration_name_timestamp() return "auto_%s" % get_migration_name_timestamp()

View File

@ -360,7 +360,7 @@ class MigrationGraph:
""" """
if nodes is None: if nodes is None:
nodes = list(self.leaf_nodes()) nodes = list(self.leaf_nodes())
if len(nodes) == 0: if not nodes:
return ProjectState() return ProjectState()
if not isinstance(nodes[0], tuple): if not isinstance(nodes[0], tuple):
nodes = [nodes] nodes = [nodes]

View File

@ -133,7 +133,7 @@ class MigrationLoader:
raise AmbiguityError( raise AmbiguityError(
"There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix) "There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix)
) )
elif len(results) == 0: elif not results:
raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix)) raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix))
else: else:
return self.disk_migrations[results[0]] return self.disk_migrations[results[0]]

View File

@ -85,7 +85,7 @@ class InteractiveMigrationQuestioner(MigrationQuestioner):
result = input("%s " % question) result = input("%s " % question)
if not result and default is not None: if not result and default is not None:
return default return default
while len(result) < 1 or result[0].lower() not in "yn": while not result or result[0].lower() not in "yn":
result = input("Please answer yes or no: ") result = input("Please answer yes or no: ")
return result[0].lower() == "y" return result[0].lower() == "y"

View File

@ -10,7 +10,7 @@ def topological_sort_as_sets(dependency_graph):
""" """
todo = dependency_graph.copy() todo = dependency_graph.copy()
while todo: while todo:
current = {node for node, deps in todo.items() if len(deps) == 0} current = {node for node, deps in todo.items() if not deps}
if not current: if not current:
raise ValueError('Cyclic dependency in graph: {}'.format( raise ValueError('Cyclic dependency in graph: {}'.format(

View File

@ -583,7 +583,7 @@ class Model(metaclass=ModelBase):
of the field will call this method. of the field will call this method.
""" """
if fields is not None: if fields is not None:
if len(fields) == 0: if not fields:
return return
if any(LOOKUP_SEP in f for f in fields): if any(LOOKUP_SEP in f for f in fields):
raise ValueError( raise ValueError(
@ -688,7 +688,7 @@ class Model(metaclass=ModelBase):
# If update_fields is empty, skip the save. We do also check for # If update_fields is empty, skip the save. We do also check for
# no-op saves later on for inheritance cases. This bailout is # no-op saves later on for inheritance cases. This bailout is
# still needed for skipping signal sending. # still needed for skipping signal sending.
if len(update_fields) == 0: if not update_fields:
return return
update_fields = frozenset(update_fields) update_fields = frozenset(update_fields)
@ -736,7 +736,7 @@ class Model(metaclass=ModelBase):
""" """
using = using or router.db_for_write(self.__class__, instance=self) using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields)) assert not (force_insert and (force_update or update_fields))
assert update_fields is None or len(update_fields) > 0 assert update_fields is None or update_fields
cls = origin = self.__class__ cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model. # Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy: if cls._meta.proxy:

View File

@ -161,7 +161,7 @@ class BaseExpression:
return [] return []
def set_source_expressions(self, exprs): def set_source_expressions(self, exprs):
assert len(exprs) == 0 assert not exprs
def _parse_expressions(self, *expressions): def _parse_expressions(self, *expressions):
return [ return [
@ -780,7 +780,7 @@ class ExpressionList(Func):
template = '%(expressions)s' template = '%(expressions)s'
def __init__(self, *expressions, **extra): def __init__(self, *expressions, **extra):
if len(expressions) == 0: if not expressions:
raise ValueError('%s requires at least one expression.' % self.__class__.__name__) raise ValueError('%s requires at least one expression.' % self.__class__.__name__)
super().__init__(*expressions, **extra) super().__init__(*expressions, **extra)

View File

@ -600,7 +600,7 @@ class ForeignObject(RelatedField):
return name, path, args, kwargs return name, path, args, kwargs
def resolve_related_fields(self): def resolve_related_fields(self):
if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields): if not self.from_fields or len(self.from_fields) != len(self.to_fields):
raise ValueError('Foreign Object from and to fields must be the same non-zero length') raise ValueError('Foreign Object from and to fields must be the same non-zero length')
if isinstance(self.remote_field.model, str): if isinstance(self.remote_field.model, str):
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
@ -1165,7 +1165,7 @@ class ManyToManyField(RelatedField):
) )
) )
if len(self._validators) > 0: if self._validators:
warnings.append( warnings.append(
checks.Warning( checks.Warning(
'ManyToManyField does not support validators.', 'ManyToManyField does not support validators.',

View File

@ -1433,7 +1433,7 @@ def prefetch_related_objects(model_instances, *related_lookups):
Populate prefetched object caches for a list of model instances based on Populate prefetched object caches for a list of model instances based on
the lookups/Prefetch instances given. the lookups/Prefetch instances given.
""" """
if len(model_instances) == 0: if not model_instances:
return # nothing to do return # nothing to do
# We need to be able to dynamically add to the list of prefetch_related # We need to be able to dynamically add to the list of prefetch_related
@ -1461,7 +1461,7 @@ def prefetch_related_objects(model_instances, *related_lookups):
through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) through_attrs = lookup.prefetch_through.split(LOOKUP_SEP)
for level, through_attr in enumerate(through_attrs): for level, through_attr in enumerate(through_attrs):
# Prepare main instances # Prepare main instances
if len(obj_list) == 0: if not obj_list:
break break
prefetch_to = lookup.get_current_prefetch_to(level) prefetch_to = lookup.get_current_prefetch_to(level)

View File

@ -1061,7 +1061,7 @@ class Query:
and get_transform(). and get_transform().
""" """
# __exact is the default lookup if one isn't given. # __exact is the default lookup if one isn't given.
if len(lookups) == 0: if not lookups:
lookups = ['exact'] lookups = ['exact']
for name in lookups[:-1]: for name in lookups[:-1]:

View File

@ -1006,7 +1006,7 @@ def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
raise ValueError( raise ValueError(
"fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label) "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label)
) )
elif len(fks_to_parent) == 0: elif not fks_to_parent:
raise ValueError( raise ValueError(
"'%s' has no field named '%s'." % (model._meta.label, fk_name) "'%s' has no field named '%s'." % (model._meta.label, fk_name)
) )
@ -1021,7 +1021,7 @@ def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
] ]
if len(fks_to_parent) == 1: if len(fks_to_parent) == 1:
fk = fks_to_parent[0] fk = fks_to_parent[0]
elif len(fks_to_parent) == 0: elif not fks_to_parent:
if can_fail: if can_fail:
return return
raise ValueError( raise ValueError(

View File

@ -568,7 +568,7 @@ def slice_filter(value, arg):
try: try:
bits = [] bits = []
for x in arg.split(':'): for x in arg.split(':'):
if len(x) == 0: if not x:
bits.append(None) bits.append(None)
else: else:
bits.append(int(x)) bits.append(int(x))

View File

@ -715,7 +715,7 @@ def firstof(parser, token):
""" """
bits = token.split_contents()[1:] bits = token.split_contents()[1:]
asvar = None asvar = None
if len(bits) < 1: if not bits:
raise TemplateSyntaxError("'firstof' statement requires at least one argument") raise TemplateSyntaxError("'firstof' statement requires at least one argument")
if len(bits) >= 2 and bits[-2] == 'as': if len(bits) >= 2 and bits[-2] == 'as':
@ -1363,7 +1363,7 @@ def url(parser, token):
asvar = bits[-1] asvar = bits[-1]
bits = bits[:-2] bits = bits[:-2]
if len(bits): if bits:
for bit in bits: for bit in bits:
match = kwarg_re.match(bit) match = kwarg_re.match(bit)
if not match: if not match:

View File

@ -114,11 +114,12 @@ class _AssertTemplateUsedContext:
if not self.test(): if not self.test():
message = self.message() message = self.message()
if len(self.rendered_templates) == 0: if self.rendered_templates:
message += ' No template was rendered.'
else:
message += ' Following templates were rendered: %s' % ( message += ' Following templates were rendered: %s' % (
', '.join(self.rendered_template_names)) ', '.join(self.rendered_template_names)
)
else:
message += ' No template was rendered.'
self.test_case.fail(message) self.test_case.fail(message)
@ -255,7 +256,7 @@ class SimpleTestCase(unittest.TestCase):
if hasattr(response, 'redirect_chain'): if hasattr(response, 'redirect_chain'):
# The request was a followed redirect # The request was a followed redirect
self.assertTrue( self.assertTrue(
len(response.redirect_chain) > 0, response.redirect_chain,
msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)" msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)"
% (response.status_code, status_code) % (response.status_code, status_code)
) )
@ -488,7 +489,7 @@ class SimpleTestCase(unittest.TestCase):
elif form_index is not None: elif form_index is not None:
non_field_errors = context[formset].forms[form_index].non_field_errors() non_field_errors = context[formset].forms[form_index].non_field_errors()
self.assertFalse( self.assertFalse(
len(non_field_errors) == 0, not non_field_errors,
msg_prefix + "The formset '%s', form %d in context %d " msg_prefix + "The formset '%s', form %d in context %d "
"does not contain any non-field errors." % (formset, form_index, i) "does not contain any non-field errors." % (formset, form_index, i)
) )
@ -501,7 +502,7 @@ class SimpleTestCase(unittest.TestCase):
else: else:
non_form_errors = context[formset].non_form_errors() non_form_errors = context[formset].non_form_errors()
self.assertFalse( self.assertFalse(
len(non_form_errors) == 0, not non_form_errors,
msg_prefix + "The formset '%s' in context %d does not " msg_prefix + "The formset '%s' in context %d does not "
"contain any non-form errors." % (formset, i) "contain any non-form errors." % (formset, i)
) )
@ -602,7 +603,7 @@ class SimpleTestCase(unittest.TestCase):
kwargs: Extra kwargs. kwargs: Extra kwargs.
""" """
callable_obj = None callable_obj = None
if len(args): if args:
callable_obj = args[0] callable_obj = args[0]
args = args[1:] args = args[1:]

View File

@ -379,7 +379,7 @@ class URLResolver:
self._local = threading.local() self._local = threading.local()
def __repr__(self): def __repr__(self):
if isinstance(self.urlconf_name, list) and len(self.urlconf_name): if isinstance(self.urlconf_name, list) and self.urlconf_name:
# Don't bother to output the whole list, it can be huge # Don't bother to output the whole list, it can be huge
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__ urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
else: else:

View File

@ -420,7 +420,7 @@ def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
nv.append('') nv.append('')
else: else:
continue continue
if len(nv[1]) or keep_blank_values: if nv[1] or keep_blank_values:
name = nv[0].replace('+', ' ') name = nv[0].replace('+', ' ')
name = unquote(name, encoding=encoding, errors=errors) name = unquote(name, encoding=encoding, errors=errors)
value = nv[1].replace('+', ' ') value = nv[1].replace('+', ' ')

View File

@ -247,7 +247,7 @@ def get_text_list(list_, last_word=gettext_lazy('or')):
>>> get_text_list([]) >>> get_text_list([])
'' ''
""" """
if len(list_) == 0: if not list_:
return '' return ''
if len(list_) == 1: if len(list_) == 1:
return str(list_[0]) return str(list_[0])

View File

@ -304,15 +304,15 @@ def gettext(message):
eol_message = message.replace('\r\n', '\n').replace('\r', '\n') eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
if len(eol_message) == 0: if eol_message:
# Return an empty value of the corresponding type if an empty message
# is given, instead of metadata, which is the default gettext behavior.
result = type(message)("")
else:
_default = _default or translation(settings.LANGUAGE_CODE) _default = _default or translation(settings.LANGUAGE_CODE)
translation_object = getattr(_active, "value", _default) translation_object = getattr(_active, "value", _default)
result = translation_object.gettext(eol_message) result = translation_object.gettext(eol_message)
else:
# Return an empty value of the corresponding type if an empty message
# is given, instead of metadata, which is the default gettext behavior.
result = type(message)('')
if isinstance(message, SafeData): if isinstance(message, SafeData):
return mark_safe(result) return mark_safe(result)

View File

@ -333,7 +333,7 @@ class BaseDateListView(MultipleObjectMixin, DateMixin, View):
if not allow_empty: if not allow_empty:
# When pagination is enabled, it's better to do a cheap query # When pagination is enabled, it's better to do a cheap query
# than to load the unpaginated queryset in memory. # than to load the unpaginated queryset in memory.
is_empty = len(qs) == 0 if paginate_by is None else not qs.exists() is_empty = not qs if paginate_by is None else not qs.exists()
if is_empty: if is_empty:
raise Http404(_("No %(verbose_name_plural)s available") % { raise Http404(_("No %(verbose_name_plural)s available") % {
'verbose_name_plural': qs.model._meta.verbose_name_plural, 'verbose_name_plural': qs.model._meta.verbose_name_plural,

View File

@ -149,7 +149,7 @@ class BaseListView(MultipleObjectMixin, View):
if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'): if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
is_empty = not self.object_list.exists() is_empty = not self.object_list.exists()
else: else:
is_empty = len(self.object_list) == 0 is_empty = not self.object_list
if is_empty: if is_empty:
raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % { raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
'class_name': self.__class__.__name__, 'class_name': self.__class__.__name__,

View File

@ -277,7 +277,7 @@ class DjangoHTMLTranslator(HTMLTranslator):
if version_text: if version_text:
title = "%s%s" % ( title = "%s%s" % (
version_text % node['version'], version_text % node['version'],
":" if len(node) else "." ":" if node else "."
) )
self.body.append('<span class="title">%s</span> ' % title) self.body.append('<span class="title">%s</span> ' % title)

View File

@ -1164,7 +1164,7 @@ class AutodetectorTests(TestCase):
def test(from_state, to_state, msg): def test(from_state, to_state, msg):
changes = self.get_changes([from_state], [to_state]) changes = self.get_changes([from_state], [to_state])
if len(changes) > 0: if changes:
ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations) ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations)
self.fail('Created operation(s) %s from %s' % (ops, msg)) self.fail('Created operation(s) %s from %s' % (ops, msg))