summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorДилян Палаузов <Dilyan.Palauzov@db.com>2017-12-27 00:14:12 +0530
committerTim Graham <timograham@gmail.com>2017-12-26 17:11:15 -0500
commit4c599ece57fa009cf3615f09497f81bfa6a585a7 (patch)
tree1f27a7e76024aaa5bc69356826061262d35d0be3
parentc21f158295d92e35caf96436bfdbbff554fc5569 (diff)
Fixed #28930 -- Simplified code with any() and all().
-rw-r--r--django/contrib/admin/helpers.py8
-rw-r--r--django/contrib/admin/options.py6
-rw-r--r--django/contrib/auth/backends.py10
-rw-r--r--django/contrib/auth/models.py5
-rw-r--r--django/contrib/staticfiles/utils.py7
-rw-r--r--django/db/models/base.py7
-rw-r--r--django/db/models/deletion.py23
-rw-r--r--django/db/models/expressions.py15
-rw-r--r--django/db/models/fields/__init__.py20
-rw-r--r--django/dispatch/dispatcher.py5
-rw-r--r--django/forms/forms.py16
-rw-r--r--django/http/multipartparser.py7
-rw-r--r--django/http/request.py6
-rw-r--r--django/template/context.py5
-rw-r--r--django/test/utils.py5
-rw-r--r--django/urls/resolvers.py7
-rw-r--r--django/utils/functional.py9
-rw-r--r--django/utils/translation/trans_real.py8
18 files changed, 54 insertions, 115 deletions
diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
index 58e92c9689..6f638417b5 100644
--- a/django/contrib/admin/helpers.py
+++ b/django/contrib/admin/helpers.py
@@ -336,10 +336,10 @@ class InlineAdminForm(AdminForm):
return True
# Also search any parents for an auto field. (The pk info is propagated to child
# models so that does not need to be checked in parents.)
- for parent in self.form._meta.model._meta.get_parent_list():
- if parent._meta.auto_field or not parent._meta.model._meta.pk.editable:
- return True
- return False
+ return any(
+ parent._meta.auto_field or not parent._meta.model._meta.pk.editable
+ for parent in self.form._meta.model._meta.get_parent_list()
+ )
def pk_field(self):
return AdminField(self.form, self.formset._pk_field.name, False)
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index 091e6935a8..14d4e712c8 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -973,11 +973,7 @@ class ModelAdmin(BaseModelAdmin):
or_queries = [models.Q(**{orm_lookup: bit})
for orm_lookup in orm_lookups]
queryset = queryset.filter(reduce(operator.or_, or_queries))
- if not use_distinct:
- for search_spec in orm_lookups:
- if lookup_needs_distinct(self.opts, search_spec):
- use_distinct = True
- break
+ use_distinct |= any(lookup_needs_distinct(self.opts, search_spec) for search_spec in orm_lookups)
return queryset, use_distinct
diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py
index 092ad29b78..ce2bffe83e 100644
--- a/django/contrib/auth/backends.py
+++ b/django/contrib/auth/backends.py
@@ -90,12 +90,10 @@ class ModelBackend:
"""
Return True if user_obj has any permissions in the given app_label.
"""
- if not user_obj.is_active:
- return False
- for perm in self.get_all_permissions(user_obj):
- if perm[:perm.index('.')] == app_label:
- return True
- return False
+ return user_obj.is_active and any(
+ perm[:perm.index('.')] == app_label
+ for perm in self.get_all_permissions(user_obj)
+ )
def get_user(self, user_id):
try:
diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py
index 3ad2e84e17..bb444a6dde 100644
--- a/django/contrib/auth/models.py
+++ b/django/contrib/auth/models.py
@@ -413,10 +413,7 @@ class AnonymousUser:
return _user_has_perm(self, perm, obj=obj)
def has_perms(self, perm_list, obj=None):
- for perm in perm_list:
- if not self.has_perm(perm, obj):
- return False
- return True
+ return all(self.has_perm(perm, obj) for perm in perm_list)
def has_module_perms(self, module):
return _user_has_module_perms(self, module)
diff --git a/django/contrib/staticfiles/utils.py b/django/contrib/staticfiles/utils.py
index 67a7cb6d9e..d4025cf124 100644
--- a/django/contrib/staticfiles/utils.py
+++ b/django/contrib/staticfiles/utils.py
@@ -10,12 +10,7 @@ def matches_patterns(path, patterns=None):
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
- if patterns is None:
- patterns = []
- for pattern in patterns:
- if fnmatch.fnmatchcase(path, pattern):
- return True
- return False
+ return any(fnmatch.fnmatchcase(path, pattern) for pattern in (patterns or []))
def get_files(storage, ignore_patterns=None, location=''):
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 27ca63fd22..36be70beb5 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -970,11 +970,8 @@ class Model(metaclass=ModelBase):
for model_class, unique_together in unique_togethers:
for check in unique_together:
- for name in check:
- # If this is an excluded field, don't add this check.
- if name in exclude:
- break
- else:
+ if not any(name in exclude for name in check):
+ # Add the check if the field isn't excluded.
unique_checks.append((model_class, tuple(check)))
# These are checks for the unique_for_<date/year/month>.
diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py
index 7c0b2c58a4..11556b46a3 100644
--- a/django/db/models/deletion.py
+++ b/django/db/models/deletion.py
@@ -139,18 +139,17 @@ class Collector:
# The use of from_field comes from the need to avoid cascade back to
# parent when parent delete is cascading to child.
opts = model._meta
- if any(link != from_field for link in opts.concrete_model._meta.parents.values()):
- return False
- # Foreign keys pointing to this model, both from m2m and other
- # models.
- for related in get_candidate_relations_to_delete(opts):
- if related.field.remote_field.on_delete is not DO_NOTHING:
- return False
- for field in model._meta.private_fields:
- if hasattr(field, 'bulk_related_objects'):
- # It's something like generic foreign key.
- return False
- return True
+ return (
+ all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
+ # Foreign keys pointing to this model.
+ all(
+ related.field.remote_field.on_delete is DO_NOTHING
+ for related in get_candidate_relations_to_delete(opts)
+ ) and (
+ # Something like generic foreign key.
+ not any(hasattr(field, 'bulk_related_objects') for field in model._meta.private_fields)
+ )
+ )
def get_del_batches(self, objs, field):
"""
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index b5090d6771..f7b1baad3a 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -200,24 +200,15 @@ class BaseExpression:
@cached_property
def contains_aggregate(self):
- for expr in self.get_source_expressions():
- if expr and expr.contains_aggregate:
- return True
- return False
+ return any(expr and expr.contains_aggregate for expr in self.get_source_expressions())
@cached_property
def contains_over_clause(self):
- for expr in self.get_source_expressions():
- if expr and expr.contains_over_clause:
- return True
- return False
+ return any(expr and expr.contains_over_clause for expr in self.get_source_expressions())
@cached_property
def contains_column_references(self):
- for expr in self.get_source_expressions():
- if expr and expr.contains_column_references:
- return True
- return False
+ return any(expr and expr.contains_column_references for expr in self.get_source_expressions())
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
"""
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index 1aafa83a1f..91336ed7d9 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -1806,18 +1806,14 @@ class IntegerField(Field):
validators_ = super().validators
internal_type = self.get_internal_type()
min_value, max_value = connection.ops.integer_field_range(internal_type)
- if min_value is not None:
- for validator in validators_:
- if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
- break
- else:
- validators_.append(validators.MinValueValidator(min_value))
- if max_value is not None:
- for validator in validators_:
- if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
- break
- else:
- validators_.append(validators.MaxValueValidator(max_value))
+ if (min_value is not None and not
+ any(isinstance(validator, validators.MinValueValidator) and
+ validator.limit_value >= min_value for validator in validators_)):
+ validators_.append(validators.MinValueValidator(min_value))
+ if (max_value is not None and not
+ any(isinstance(validator, validators.MaxValueValidator) and
+ validator.limit_value <= max_value for validator in validators_)):
+ validators_.append(validators.MaxValueValidator(max_value))
return validators_
def get_prep_value(self, value):
diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py
index 5e1f83890f..6488c7fbd4 100644
--- a/django/dispatch/dispatcher.py
+++ b/django/dispatch/dispatcher.py
@@ -106,10 +106,7 @@ class Signal:
with self.lock:
self._clear_dead_receivers()
- for r_key, _ in self.receivers:
- if r_key == lookup_key:
- break
- else:
+ if not any(r_key == lookup_key for r_key, _ in self.receivers):
self.receivers.append((lookup_key, receiver))
self.sender_receivers_cache.clear()
diff --git a/django/forms/forms.py b/django/forms/forms.py
index d8a05e3583..1be7814993 100644
--- a/django/forms/forms.py
+++ b/django/forms/forms.py
@@ -351,13 +351,10 @@ class BaseForm:
del self.cleaned_data[field]
def has_error(self, field, code=None):
- if code is None:
- return field in self.errors
- if field in self.errors:
- for error in self.errors.as_data()[field]:
- if error.code == code:
- return True
- return False
+ return field in self.errors and (
+ code is None or
+ any(error.code == code for error in self.errors.as_data()[field])
+ )
def full_clean(self):
"""
@@ -464,10 +461,7 @@ class BaseForm:
Return True if the form needs to be multipart-encoded, i.e. it has
FileInput, or False otherwise.
"""
- for field in self.fields.values():
- if field.widget.needs_multipart_form:
- return True
- return False
+ return any(field.widget.needs_multipart_form for field in self.fields.values())
def hidden_fields(self):
"""
diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
index 789a6610a5..f6f12ca718 100644
--- a/django/http/multipartparser.py
+++ b/django/http/multipartparser.py
@@ -277,11 +277,8 @@ class MultiPartParser:
exhaust(self._input_data)
# Signal that the upload has completed.
- for handler in handlers:
- retval = handler.upload_complete()
- if retval:
- break
-
+ # any() shortcircuits if a handler's upload_complete() returns a value.
+ any(handler.upload_complete() for handler in handlers)
self._post._mutable = False
return self._post, self._files
diff --git a/django/http/request.py b/django/http/request.py
index 5a14c2a41a..2538e0a012 100644
--- a/django/http/request.py
+++ b/django/http/request.py
@@ -567,8 +567,4 @@ def validate_host(host, allowed_hosts):
Return ``True`` for a valid host, ``False`` otherwise.
"""
- for pattern in allowed_hosts:
- if pattern == '*' or is_same_domain(host, pattern):
- return True
-
- return False
+ return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
diff --git a/django/template/context.py b/django/template/context.py
index ec9abf7655..8218e86491 100644
--- a/django/template/context.py
+++ b/django/template/context.py
@@ -87,10 +87,7 @@ class BaseContext:
del self.dicts[-1][key]
def __contains__(self, key):
- for d in self.dicts:
- if key in d:
- return True
- return False
+ return any(key in d for d in self.dicts)
def get(self, key, otherwise=None):
for d in reversed(self.dicts):
diff --git a/django/test/utils.py b/django/test/utils.py
index 1678bf0de4..c1c38ca096 100644
--- a/django/test/utils.py
+++ b/django/test/utils.py
@@ -553,10 +553,7 @@ def compare_xml(want, got):
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
- for want, got in zip(want_children, got_children):
- if not check_element(want, got):
- return False
- return True
+ return all(check_element(want, got) for want, got in zip(want_children, got_children))
def first_node(document):
for node in document.childNodes:
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py
index 758eaef218..3f48d72fed 100644
--- a/django/urls/resolvers.py
+++ b/django/urls/resolvers.py
@@ -572,12 +572,7 @@ class URLResolver:
else:
if set(kwargs).symmetric_difference(params).difference(defaults):
continue
- matches = True
- for k, v in defaults.items():
- if kwargs.get(k, v) != v:
- matches = False
- break
- if not matches:
+ if any(kwargs.get(k, v) != v for k, v in defaults.items()):
continue
candidate_subs = kwargs
# Convert the candidate subs to text using Converter.to_url().
diff --git a/django/utils/functional.py b/django/utils/functional.py
index 0da1fffa2b..146a2e8dc2 100644
--- a/django/utils/functional.py
+++ b/django/utils/functional.py
@@ -190,12 +190,9 @@ def keep_lazy(*resultclasses):
@wraps(func)
def wrapper(*args, **kwargs):
- for arg in itertools.chain(args, kwargs.values()):
- if isinstance(arg, Promise):
- break
- else:
- return func(*args, **kwargs)
- return lazy_func(*args, **kwargs)
+ if any(isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values())):
+ return lazy_func(*args, **kwargs)
+ return func(*args, **kwargs)
return wrapper
return decorator
diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
index cb8e79287d..74c21d97e9 100644
--- a/django/utils/translation/trans_real.py
+++ b/django/utils/translation/trans_real.py
@@ -394,10 +394,10 @@ def check_for_language(lang_code):
# First, a quick check to make sure lang_code is well-formed (#21458)
if lang_code is None or not language_code_re.search(lang_code):
return False
- for path in all_locale_paths():
- if gettext_module.find('django', path, [to_locale(lang_code)]) is not None:
- return True
- return False
+ return any(
+ gettext_module.find('django', path, [to_locale(lang_code)]) is not None
+ for path in all_locale_paths()
+ )
@functools.lru_cache()