Ticket #28930: any_all.patch

File any_all.patch, 17.4 KB (added by Дилян Палаузов, 7 years ago)
  • django/contrib/admin/helpers.py

    diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
    a b class InlineAdminForm(AdminForm):  
    336336            return True
    337337        # Also search any parents for an auto field. (The pk info is propagated to child
    338338        # models so that does not need to be checked in parents.)
    339         for parent in self.form._meta.model._meta.get_parent_list():
    340             if parent._meta.auto_field or not parent._meta.model._meta.pk.editable:
    341                 return True
    342         return False
     339        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())
    343340
    344341    def pk_field(self):
    345342        return AdminField(self.form, self.formset._pk_field.name, False)
  • django/contrib/admin/options.py

    diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
    a b class ModelAdmin(BaseModelAdmin):  
    973973                or_queries = [models.Q(**{orm_lookup: bit})
    974974                              for orm_lookup in orm_lookups]
    975975                queryset = queryset.filter(reduce(operator.or_, or_queries))
    976             if not use_distinct:
    977                 for search_spec in orm_lookups:
    978                     if lookup_needs_distinct(self.opts, search_spec):
    979                         use_distinct = True
    980                         break
     976            use_distinct = use_distinct or any(lookup_needs_distinct(self.opts, search_spec) for search_spec in orm_lookups)
    981977
    982978        return queryset, use_distinct
    983979
  • django/contrib/admin/utils.py

    diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
    a b def lookup_needs_distinct(opts, lookup_path):  
    3939                # This field is a relation; update opts to follow the relation.
    4040                path_info = field.get_path_info()
    4141                opts = path_info[-1].to_opts
    42                 if any(path.m2m for path in path_info):
    43                     # This field is a m2m relation so distinct must be called.
    44                     return True
     42                return any(path.m2m for path in path_info)
     43                # This field is a m2m relation so distinct must be called.
    4544    return False
    4645
    4746
  • django/contrib/auth/backends.py

    diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py
    a b class ModelBackend:  
    9090        """
    9191        Return True if user_obj has any permissions in the given app_label.
    9292        """
    93         if not user_obj.is_active:
    94             return False
    95         for perm in self.get_all_permissions(user_obj):
    96             if perm[:perm.index('.')] == app_label:
    97                 return True
    98         return False
     93        return user_obj.is_active and any(perm[:perm.index('.')] == app_label for perm in self.get_all_permissions(user_obj))
    9994
    10095    def get_user(self, user_id):
    10196        try:
  • django/contrib/auth/models.py

    diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py
    a b class AnonymousUser:  
    413413        return _user_has_perm(self, perm, obj=obj)
    414414
    415415    def has_perms(self, perm_list, obj=None):
    416         for perm in perm_list:
    417             if not self.has_perm(perm, obj):
    418                 return False
    419         return True
     416        return all(self.has_perm(perm, obj) for perm in perm_list)
    420417
    421418    def has_module_perms(self, module):
    422419        return _user_has_module_perms(self, module)
  • django/contrib/staticfiles/utils.py

    diff --git a/django/contrib/staticfiles/utils.py b/django/contrib/staticfiles/utils.py
    a b def matches_patterns(path, patterns=None):  
    1010    Return True or False depending on whether the ``path`` should be
    1111    ignored (if it matches any pattern in ``ignore_patterns``).
    1212    """
    13     if patterns is None:
    14         patterns = []
    15     for pattern in patterns:
    16         if fnmatch.fnmatchcase(path, pattern):
    17             return True
    18     return False
     13    return any(fnmatch.fnmatchcase(path, pattern) for pattern in (patterns or []))
    1914
    2015
    2116def get_files(storage, ignore_patterns=None, location=''):
  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    a b class Model(metaclass=ModelBase):  
    970970
    971971        for model_class, unique_together in unique_togethers:
    972972            for check in unique_together:
    973                 for name in check:
     973                if not any(name in excluce for name in check):
    974974                    # If this is an excluded field, don't add this check.
    975                     if name in exclude:
    976                         break
    977                 else:
    978975                    unique_checks.append((model_class, tuple(check)))
    979976
    980977        # These are checks for the unique_for_<date/year/month>.
  • django/db/models/deletion.py

    diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py
    a b class Collector:  
    139139        # The use of from_field comes from the need to avoid cascade back to
    140140        # parent when parent delete is cascading to child.
    141141        opts = model._meta
    142         if any(link != from_field for link in opts.concrete_model._meta.parents.values()):
    143             return False
     142        return (
     143            all(link == from_field for link in opts.concrete_model._meta.parents.values()) and
    144144        # Foreign keys pointing to this model, both from m2m and other
    145145        # models.
    146         for related in get_candidate_relations_to_delete(opts):
    147             if related.field.remote_field.on_delete is not DO_NOTHING:
    148                 return False
    149         for field in model._meta.private_fields:
    150             if hasattr(field, 'bulk_related_objects'):
     146            all(related.field.remote_field.on_delete is DO_NOTHING for related in get_candidate_relations_to_delete(opts)) and
     147            not any(hasattr(field, 'bulk_related_objects') for field in model._meta.private_fields)
    151148                # It's something like generic foreign key.
    152                 return False
    153         return True
     149            )
    154150
    155151    def get_del_batches(self, objs, field):
    156152        """
  • django/db/models/expressions.py

    diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
    a b class BaseExpression:  
    200200
    201201    @cached_property
    202202    def contains_aggregate(self):
    203         for expr in self.get_source_expressions():
    204             if expr and expr.contains_aggregate:
    205                 return True
    206         return False
     203        return any(expr and expr.contains_aggregate for expr in self.get_source_expressions())
    207204
    208205    @cached_property
    209206    def contains_over_clause(self):
    210         for expr in self.get_source_expressions():
    211             if expr and expr.contains_over_clause:
    212                 return True
    213         return False
     207        return any(expr and expr.contains_over_clause for expr in self.get_source_expressions())
    214208
    215209    @cached_property
    216210    def contains_column_references(self):
    217         for expr in self.get_source_expressions():
    218             if expr and expr.contains_column_references:
    219                 return True
    220         return False
     211        return any(expr and expr.contains_column_references for expr in self.get_source_expressions())
    221212
    222213    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
    223214        """
  • django/db/models/fields/__init__.py

    diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
    a b class IntegerField(Field):  
    18061806        validators_ = super().validators
    18071807        internal_type = self.get_internal_type()
    18081808        min_value, max_value = connection.ops.integer_field_range(internal_type)
    1809         if min_value is not None:
    1810             for validator in validators_:
    1811                 if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
    1812                     break
    1813             else:
     1809        if min_value is not None and not any(isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value for validator in validators_):
    18141810                validators_.append(validators.MinValueValidator(min_value))
    1815         if max_value is not None:
    1816             for validator in validators_:
    1817                 if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
    1818                     break
    1819             else:
     1811        if max_value is not None and not any(isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value for validator in validators_):
    18201812                validators_.append(validators.MaxValueValidator(max_value))
    18211813        return validators_
    18221814
  • django/dispatch/dispatcher.py

    diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py
    a b class Signal:  
    106106
    107107        with self.lock:
    108108            self._clear_dead_receivers()
    109             for r_key, _ in self.receivers:
    110                 if r_key == lookup_key:
    111                     break
    112             else:
     109            if not any(r_key == lookup_key for r_key, _ in self.receivers):
    113110                self.receivers.append((lookup_key, receiver))
    114111            self.sender_receivers_cache.clear()
    115112
  • django/forms/forms.py

    diff --git a/django/forms/forms.py b/django/forms/forms.py
    a b class BaseForm:  
    351351                del self.cleaned_data[field]
    352352
    353353    def has_error(self, field, code=None):
    354         if code is None:
    355             return field in self.errors
    356         if field in self.errors:
    357             for error in self.errors.as_data()[field]:
    358                 if error.code == code:
    359                     return True
    360         return False
     354        return field in self.errors and (code is None or any(error.code == code for error in self.errors.as_data()[field]))
    361355
    362356    def full_clean(self):
    363357        """
    class BaseForm:  
    464458        Return True if the form needs to be multipart-encoded, i.e. it has
    465459        FileInput, or False otherwise.
    466460        """
    467         for field in self.fields.values():
    468             if field.widget.needs_multipart_form:
    469                 return True
    470         return False
     461        return any(field.widget.needs_multipart_form for field in self.fields.values())
    471462
    472463    def hidden_fields(self):
    473464        """
  • django/http/multipartparser.py

    diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
    a b class MultiPartParser:  
    277277            exhaust(self._input_data)
    278278
    279279        # Signal that the upload has completed.
    280         for handler in handlers:
    281             retval = handler.upload_complete()
    282             if retval:
    283                 break
    284 
     280        any(handler.upload_complete() for handler in handlers)
    285281        self._post._mutable = False
    286282        return self._post, self._files
    287283
  • django/http/request.py

    diff --git a/django/http/request.py b/django/http/request.py
    a b def validate_host(host, allowed_hosts):  
    567567
    568568    Return ``True`` for a valid host, ``False`` otherwise.
    569569    """
    570     for pattern in allowed_hosts:
    571         if pattern == '*' or is_same_domain(host, pattern):
    572             return True
    573 
    574     return False
     570    return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
  • django/template/context.py

    diff --git a/django/template/context.py b/django/template/context.py
    a b class BaseContext:  
    8787        del self.dicts[-1][key]
    8888
    8989    def __contains__(self, key):
    90         for d in self.dicts:
    91             if key in d:
    92                 return True
    93         return False
     90        return any(key in d for d in self.dicts)
    9491
    9592    def get(self, key, otherwise=None):
    9693        for d in reversed(self.dicts):
  • django/test/utils.py

    diff --git a/django/test/utils.py b/django/test/utils.py
    a b def compare_xml(want, got):  
    553553        got_children = children(got_element)
    554554        if len(want_children) != len(got_children):
    555555            return False
    556         for want, got in zip(want_children, got_children):
    557             if not check_element(want, got):
    558                 return False
    559         return True
     556        return all(check_element(want, got) for want, got in zip(want_children, got_children))
    560557
    561558    def first_node(document):
    562559        for node in document.childNodes:
  • django/urls/resolvers.py

    diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py
    a b class URLResolver:  
    572572                else:
    573573                    if set(kwargs).symmetric_difference(params).difference(defaults):
    574574                        continue
    575                     matches = True
    576                     for k, v in defaults.items():
    577                         if kwargs.get(k, v) != v:
    578                             matches = False
    579                             break
    580                     if not matches:
     575                    if any(kwargs.get(k, v) != v for k, v in defaults.items()):
    581576                        continue
    582577                    candidate_subs = kwargs
    583578                # Convert the candidate subs to text using Converter.to_url().
  • django/utils/functional.py

    diff --git a/django/utils/functional.py b/django/utils/functional.py
    a b def keep_lazy(*resultclasses):  
    190190
    191191        @wraps(func)
    192192        def wrapper(*args, **kwargs):
    193             for arg in itertools.chain(args, kwargs.values()):
    194                 if isinstance(arg, Promise):
    195                     break
    196             else:
    197                 return func(*args, **kwargs)
    198             return lazy_func(*args, **kwargs)
     193            if any(isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values())):
     194                return lazy_func(*args, **kwargs)
     195            return func(*args, **kwargs)
    199196        return wrapper
    200197    return decorator
    201198
  • django/utils/http.py

    diff --git a/django/utils/http.py b/django/utils/http.py
    a b def _urlsplit(url, scheme='', allow_fragments=True):  
    326326    url, scheme, _coerce_result = _coerce_args(url, scheme)
    327327    netloc = query = fragment = ''
    328328    i = url.find(':')
    329     if i > 0:
    330         for c in url[:i]:
    331             if c not in scheme_chars:
    332                 break
    333         else:
    334             scheme, url = url[:i].lower(), url[i + 1:]
     329    if i > 0 and all(c in scheme_chars for c in url[:i]):
     330        scheme, url = url[:i].lower(), url[i + 1:]
    335331
    336332    if url[:2] == '//':
    337333        netloc, url = _splitnetloc(url, 2)
  • django/utils/six.py

    diff --git a/django/utils/six.py b/django/utils/six.py
    a b if print_ is None:  
    751751                raise TypeError("end must be None or a string")
    752752        if kwargs:
    753753            raise TypeError("invalid keyword arguments to print()")
    754         if not want_unicode:
    755             for arg in args:
    756                 if isinstance(arg, unicode):
    757                     want_unicode = True
    758                     break
    759         if want_unicode:
     754        if want_unicode or any(isinstance(arg, unicode) for arg in args):
    760755            newline = unicode("\n")
    761756            space = unicode(" ")
    762757        else:
  • django/utils/translation/trans_real.py

    diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
    a b def check_for_language(lang_code):  
    394394    # First, a quick check to make sure lang_code is well-formed (#21458)
    395395    if lang_code is None or not language_code_re.search(lang_code):
    396396        return False
    397     for path in all_locale_paths():
    398         if gettext_module.find('django', path, [to_locale(lang_code)]) is not None:
    399             return True
    400     return False
     397    return any(gettext_module.find('django', path, [to_locale(lang_code)]) is not None for path in all_locale_paths())
    401398
    402399
    403400@functools.lru_cache()
  • tests/schema/tests.py

    diff --git a/tests/schema/tests.py b/tests/schema/tests.py
    a b class SchemaTests(TransactionTestCase):  
    14301430            editor.create_model(Author)
    14311431        # Ensure the constraint exists
    14321432        constraints = self.get_constraints(Author._meta.db_table)
    1433         for details in constraints.values():
    1434             if details['columns'] == ["height"] and details['check']:
    1435                 break
    1436         else:
     1433        if not any(details['columns'] == ["height"] and details['check'] for details in constraints.values()):
    14371434            self.fail("No check constraint for height found")
    14381435        # Alter the column to remove it
    14391436        old_field = Author._meta.get_field("height")
    class SchemaTests(TransactionTestCase):  
    14501447        with connection.schema_editor() as editor:
    14511448            editor.alter_field(Author, new_field, new_field2, strict=True)
    14521449        constraints = self.get_constraints(Author._meta.db_table)
    1453         for details in constraints.values():
    1454             if details['columns'] == ["height"] and details['check']:
    1455                 break
    1456         else:
     1450        if not any(details['columns'] == ["height"] and details['check'] for details in constraints.values()):
    14571451            self.fail("No check constraint for height found")
    14581452
    14591453    def test_unique(self):
Back to Top