Fixed #28930 -- Simplified code with any() and all().

This commit is contained in:
Дилян Палаузов 2017-12-27 00:14:12 +05:30 committed by Tim Graham
parent c21f158295
commit 4c599ece57
18 changed files with 54 additions and 115 deletions

View File

@ -336,10 +336,10 @@ class InlineAdminForm(AdminForm):
return True return True
# Also search any parents for an auto field. (The pk info is propagated to child # 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.) # models so that does not need to be checked in parents.)
for parent in self.form._meta.model._meta.get_parent_list(): return any(
if parent._meta.auto_field or not parent._meta.model._meta.pk.editable: parent._meta.auto_field or not parent._meta.model._meta.pk.editable
return True for parent in self.form._meta.model._meta.get_parent_list()
return False )
def pk_field(self): def pk_field(self):
return AdminField(self.form, self.formset._pk_field.name, False) return AdminField(self.form, self.formset._pk_field.name, False)

View File

@ -973,11 +973,7 @@ class ModelAdmin(BaseModelAdmin):
or_queries = [models.Q(**{orm_lookup: bit}) or_queries = [models.Q(**{orm_lookup: bit})
for orm_lookup in orm_lookups] for orm_lookup in orm_lookups]
queryset = queryset.filter(reduce(operator.or_, or_queries)) queryset = queryset.filter(reduce(operator.or_, or_queries))
if not use_distinct: use_distinct |= any(lookup_needs_distinct(self.opts, search_spec) for search_spec in orm_lookups)
for search_spec in orm_lookups:
if lookup_needs_distinct(self.opts, search_spec):
use_distinct = True
break
return queryset, use_distinct return queryset, use_distinct

View File

@ -90,12 +90,10 @@ class ModelBackend:
""" """
Return True if user_obj has any permissions in the given app_label. Return True if user_obj has any permissions in the given app_label.
""" """
if not user_obj.is_active: return user_obj.is_active and any(
return False perm[:perm.index('.')] == app_label
for perm in self.get_all_permissions(user_obj): for perm in self.get_all_permissions(user_obj)
if perm[:perm.index('.')] == app_label: )
return True
return False
def get_user(self, user_id): def get_user(self, user_id):
try: try:

View File

@ -413,10 +413,7 @@ class AnonymousUser:
return _user_has_perm(self, perm, obj=obj) return _user_has_perm(self, perm, obj=obj)
def has_perms(self, perm_list, obj=None): def has_perms(self, perm_list, obj=None):
for perm in perm_list: return all(self.has_perm(perm, obj) for perm in perm_list)
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, module): def has_module_perms(self, module):
return _user_has_module_perms(self, module) return _user_has_module_perms(self, module)

View File

@ -10,12 +10,7 @@ def matches_patterns(path, patterns=None):
Return True or False depending on whether the ``path`` should be Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``). ignored (if it matches any pattern in ``ignore_patterns``).
""" """
if patterns is None: return any(fnmatch.fnmatchcase(path, pattern) for pattern in (patterns or []))
patterns = []
for pattern in patterns:
if fnmatch.fnmatchcase(path, pattern):
return True
return False
def get_files(storage, ignore_patterns=None, location=''): def get_files(storage, ignore_patterns=None, location=''):

View File

@ -970,11 +970,8 @@ class Model(metaclass=ModelBase):
for model_class, unique_together in unique_togethers: for model_class, unique_together in unique_togethers:
for check in unique_together: for check in unique_together:
for name in check: if not any(name in exclude for name in check):
# If this is an excluded field, don't add this check. # Add the check if the field isn't excluded.
if name in exclude:
break
else:
unique_checks.append((model_class, tuple(check))) unique_checks.append((model_class, tuple(check)))
# These are checks for the unique_for_<date/year/month>. # These are checks for the unique_for_<date/year/month>.

View File

@ -139,18 +139,17 @@ class Collector:
# The use of from_field comes from the need to avoid cascade back to # The use of from_field comes from the need to avoid cascade back to
# parent when parent delete is cascading to child. # parent when parent delete is cascading to child.
opts = model._meta opts = model._meta
if any(link != from_field for link in opts.concrete_model._meta.parents.values()): return (
return False all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
# Foreign keys pointing to this model, both from m2m and other # Foreign keys pointing to this model.
# models. all(
for related in get_candidate_relations_to_delete(opts): related.field.remote_field.on_delete is DO_NOTHING
if related.field.remote_field.on_delete is not DO_NOTHING: for related in get_candidate_relations_to_delete(opts)
return False ) and (
for field in model._meta.private_fields: # Something like generic foreign key.
if hasattr(field, 'bulk_related_objects'): not any(hasattr(field, 'bulk_related_objects') for field in model._meta.private_fields)
# It's something like generic foreign key. )
return False )
return True
def get_del_batches(self, objs, field): def get_del_batches(self, objs, field):
""" """

View File

@ -200,24 +200,15 @@ class BaseExpression:
@cached_property @cached_property
def contains_aggregate(self): def contains_aggregate(self):
for expr in self.get_source_expressions(): return any(expr and expr.contains_aggregate for expr in self.get_source_expressions())
if expr and expr.contains_aggregate:
return True
return False
@cached_property @cached_property
def contains_over_clause(self): def contains_over_clause(self):
for expr in self.get_source_expressions(): return any(expr and expr.contains_over_clause for expr in self.get_source_expressions())
if expr and expr.contains_over_clause:
return True
return False
@cached_property @cached_property
def contains_column_references(self): def contains_column_references(self):
for expr in self.get_source_expressions(): return any(expr and expr.contains_column_references for expr in self.get_source_expressions())
if expr and expr.contains_column_references:
return True
return False
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
""" """

View File

@ -1806,17 +1806,13 @@ class IntegerField(Field):
validators_ = super().validators validators_ = super().validators
internal_type = self.get_internal_type() internal_type = self.get_internal_type()
min_value, max_value = connection.ops.integer_field_range(internal_type) min_value, max_value = connection.ops.integer_field_range(internal_type)
if min_value is not None: if (min_value is not None and not
for validator in validators_: any(isinstance(validator, validators.MinValueValidator) and
if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value: validator.limit_value >= min_value for validator in validators_)):
break
else:
validators_.append(validators.MinValueValidator(min_value)) validators_.append(validators.MinValueValidator(min_value))
if max_value is not None: if (max_value is not None and not
for validator in validators_: any(isinstance(validator, validators.MaxValueValidator) and
if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value: validator.limit_value <= max_value for validator in validators_)):
break
else:
validators_.append(validators.MaxValueValidator(max_value)) validators_.append(validators.MaxValueValidator(max_value))
return validators_ return validators_

View File

@ -106,10 +106,7 @@ class Signal:
with self.lock: with self.lock:
self._clear_dead_receivers() self._clear_dead_receivers()
for r_key, _ in self.receivers: if not any(r_key == lookup_key for r_key, _ in self.receivers):
if r_key == lookup_key:
break
else:
self.receivers.append((lookup_key, receiver)) self.receivers.append((lookup_key, receiver))
self.sender_receivers_cache.clear() self.sender_receivers_cache.clear()

View File

@ -351,13 +351,10 @@ class BaseForm:
del self.cleaned_data[field] del self.cleaned_data[field]
def has_error(self, field, code=None): def has_error(self, field, code=None):
if code is None: return field in self.errors and (
return field in self.errors code is None or
if field in self.errors: any(error.code == code for error in self.errors.as_data()[field])
for error in self.errors.as_data()[field]: )
if error.code == code:
return True
return False
def full_clean(self): def full_clean(self):
""" """
@ -464,10 +461,7 @@ class BaseForm:
Return True if the form needs to be multipart-encoded, i.e. it has Return True if the form needs to be multipart-encoded, i.e. it has
FileInput, or False otherwise. FileInput, or False otherwise.
""" """
for field in self.fields.values(): return any(field.widget.needs_multipart_form for field in self.fields.values())
if field.widget.needs_multipart_form:
return True
return False
def hidden_fields(self): def hidden_fields(self):
""" """

View File

@ -277,11 +277,8 @@ class MultiPartParser:
exhaust(self._input_data) exhaust(self._input_data)
# Signal that the upload has completed. # Signal that the upload has completed.
for handler in handlers: # any() shortcircuits if a handler's upload_complete() returns a value.
retval = handler.upload_complete() any(handler.upload_complete() for handler in handlers)
if retval:
break
self._post._mutable = False self._post._mutable = False
return self._post, self._files return self._post, self._files

View File

@ -567,8 +567,4 @@ def validate_host(host, allowed_hosts):
Return ``True`` for a valid host, ``False`` otherwise. Return ``True`` for a valid host, ``False`` otherwise.
""" """
for pattern in allowed_hosts: return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
if pattern == '*' or is_same_domain(host, pattern):
return True
return False

View File

@ -87,10 +87,7 @@ class BaseContext:
del self.dicts[-1][key] del self.dicts[-1][key]
def __contains__(self, key): def __contains__(self, key):
for d in self.dicts: return any(key in d for d in self.dicts)
if key in d:
return True
return False
def get(self, key, otherwise=None): def get(self, key, otherwise=None):
for d in reversed(self.dicts): for d in reversed(self.dicts):

View File

@ -553,10 +553,7 @@ def compare_xml(want, got):
got_children = children(got_element) got_children = children(got_element)
if len(want_children) != len(got_children): if len(want_children) != len(got_children):
return False return False
for want, got in zip(want_children, got_children): return all(check_element(want, got) for want, got in zip(want_children, got_children))
if not check_element(want, got):
return False
return True
def first_node(document): def first_node(document):
for node in document.childNodes: for node in document.childNodes:

View File

@ -572,12 +572,7 @@ class URLResolver:
else: else:
if set(kwargs).symmetric_difference(params).difference(defaults): if set(kwargs).symmetric_difference(params).difference(defaults):
continue continue
matches = True if any(kwargs.get(k, v) != v for k, v in defaults.items()):
for k, v in defaults.items():
if kwargs.get(k, v) != v:
matches = False
break
if not matches:
continue continue
candidate_subs = kwargs candidate_subs = kwargs
# Convert the candidate subs to text using Converter.to_url(). # Convert the candidate subs to text using Converter.to_url().

View File

@ -190,12 +190,9 @@ def keep_lazy(*resultclasses):
@wraps(func) @wraps(func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
for arg in itertools.chain(args, kwargs.values()): if any(isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values())):
if isinstance(arg, Promise):
break
else:
return func(*args, **kwargs)
return lazy_func(*args, **kwargs) return lazy_func(*args, **kwargs)
return func(*args, **kwargs)
return wrapper return wrapper
return decorator return decorator

View File

@ -394,10 +394,10 @@ def check_for_language(lang_code):
# First, a quick check to make sure lang_code is well-formed (#21458) # 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): if lang_code is None or not language_code_re.search(lang_code):
return False return False
for path in all_locale_paths(): return any(
if gettext_module.find('django', path, [to_locale(lang_code)]) is not None: gettext_module.find('django', path, [to_locale(lang_code)]) is not None
return True for path in all_locale_paths()
return False )
@functools.lru_cache() @functools.lru_cache()