Ticket #28860: less-len.patch

File less-len.patch, 18.3 KB (added by Дилян Палаузов, 7 years ago)
  • django/contrib/contenttypes/admin.py

    commit a8c2ba041d496a80689c0735b606739b743b6876
    Author: Дилян Палаузов <Dilyan.Palauzov@db.com>
    Date:   Wed Nov 29 17:06:40 2017 +0100
    
        Optimize usage of len()
        
        "if len(x)" is the same as "if bool(len(x))" which is the same as "if x".
        
        len(x) can return either zero or a positive integer, hence if len(x) < 1
        is the same as "if len(x) == 0" <=> "if not x".
    
    diff --git a/django/contrib/contenttypes/admin.py b/django/contrib/contenttypes/admin.py
    index 063c376..dd20249 100644
    a b class GenericInlineModelAdminChecks(InlineModelAdminChecks):  
    2525            f for f in obj.model._meta.private_fields
    2626            if isinstance(f, GenericForeignKey)
    2727        ]
    28         if len(gfks) == 0:
     28        if not gfks:
    2929            return [
    3030                checks.Error(
    3131                    "'%s.%s' has no GenericForeignKey." % (
  • django/contrib/flatpages/templatetags/flatpages.py

    diff --git a/django/contrib/flatpages/templatetags/flatpages.py b/django/contrib/flatpages/templatetags/flatpages.py
    index 985083d..edc8404 100644
    a b def get_flatpages(parser, token):  
    7474                      "['url_starts_with'] [for user] as context_name" %
    7575                      {'tag_name': bits[0]})
    7676    # Must have at 3-6 bits in the tag
    77     if len(bits) >= 3 and len(bits) <= 6:
     77    if 3 <= len(bits) <= 6:
    7878
    7979        # If there's an even number of bits, there's no prefix
    8080        if len(bits) % 2 == 0:
  • django/contrib/gis/geos/polygon.py

    diff --git a/django/contrib/gis/geos/polygon.py b/django/contrib/gis/geos/polygon.py
    index 26fcfbf..9ed3b94 100644
    a b class Polygon(GEOSGeometry):  
    3737
    3838        # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility]
    3939        if n_holes == 1 and isinstance(init_holes[0], (tuple, list)):
    40             if len(init_holes[0]) == 0:
     40            if not init_holes[0]:
    4141                init_holes = ()
    4242                n_holes = 0
    4343            elif isinstance(init_holes[0][0], LinearRing):
  • django/core/management/__init__.py

    diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py
    index 77c060c..d6395e0 100644
    a b class ManagementUtility:  
    351351        if subcommand == 'help':
    352352            if '--commands' in args:
    353353                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
    354             elif len(options.args) < 1:
     354            elif not options.args:
    355355                sys.stdout.write(self.main_help_text() + '\n')
    356356            else:
    357357                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
  • django/core/management/commands/createcachetable.py

    diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py
    index 8f9482d..3acb3dd 100644
    a b class Command(BaseCommand):  
    3333        db = options['database']
    3434        self.verbosity = options['verbosity']
    3535        dry_run = options['dry_run']
    36         if len(tablenames):
     36        if tablenames:
    3737            # Legacy behavior, tablename specified as argument
    3838            for tablename in tablenames:
    3939                self.create_table(db, tablename, dry_run)
  • django/core/management/commands/dumpdata.py

    diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py
    index d32b191..ae00a3b 100644
    a b class Command(BaseCommand):  
    8484
    8585        excluded_models, excluded_apps = parse_apps_and_model_labels(excludes)
    8686
    87         if len(app_labels) == 0:
     87        if not app_labels:
    8888            if primary_keys:
    8989                raise CommandError("You can only use --pks option with one model")
    9090            app_list = OrderedDict.fromkeys(
  • django/core/management/commands/makemigrations.py

    diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py
    index 45fce19..871bd39 100644
    a b class Command(BaseCommand):  
    164164            if self.verbosity >= 1:
    165165                if len(app_labels) == 1:
    166166                    self.stdout.write("No changes detected in app '%s'" % app_labels.pop())
    167                 elif len(app_labels) > 1:
     167                elif app_labels:
    168168                    self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels)))
    169169                else:
    170170                    self.stdout.write("No changes detected")
  • django/db/backends/oracle/base.py

    diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
    index ae77de5..b697758 100644
    a b class FormatStylePlaceholderCursor:  
    476476            # Handle params as dict
    477477            args = {k: ":%s" % k for k in params}
    478478            query = query % args
    479         elif unify_by_values and len(params) > 0:
     479        elif unify_by_values and params:
    480480            # Handle params as a dict with unified query parameters by their
    481481            # values. It can be used only in single query execute() because
    482482            # executemany() shares the formatted query with each of the params
  • django/db/backends/postgresql/operations.py

    diff --git a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py
    index 489aaf2..46d816a 100644
    a b class DatabaseOperations(BaseDatabaseOperations):  
    132132        for sequence_info in sequences:
    133133            table_name = sequence_info['table']
    134134            column_name = sequence_info['column']
    135             if not (column_name and len(column_name) > 0):
     135            if not column_name:
    136136                # This will be the case if it's an m2m using an autogenerated
    137137                # intermediate table (see BaseDatabaseIntrospection.sequence_list)
    138138                column_name = 'id'
  • django/db/migrations/autodetector.py

    diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
    index a7e5949..b58e4fc 100644
    a b class MigrationAutodetector:  
    12171217                return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
    12181218            if isinstance(ops[0], operations.RemoveField):
    12191219                return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
    1220         elif len(ops) > 1:
     1220        elif ops:
    12211221            if all(isinstance(o, operations.CreateModel) for o in ops):
    12221222                return "_".join(sorted(o.name_lower for o in ops))
    12231223        return "auto_%s" % get_migration_name_timestamp()
  • django/db/migrations/graph.py

    diff --git a/django/db/migrations/graph.py b/django/db/migrations/graph.py
    index 687a9b3..4bb66b7 100644
    a b class MigrationGraph:  
    360360        """
    361361        if nodes is None:
    362362            nodes = list(self.leaf_nodes())
    363         if len(nodes) == 0:
     363        if not nodes:
    364364            return ProjectState()
    365365        if not isinstance(nodes[0], tuple):
    366366            nodes = [nodes]
  • django/db/migrations/loader.py

    diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py
    index ae79777..beae84f 100644
    a b class MigrationLoader:  
    133133            raise AmbiguityError(
    134134                "There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix)
    135135            )
    136         if len(results) == 0:
     136        if not results:
    137137            raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix))
    138138        return self.disk_migrations[results[0]]
    139139
  • django/db/migrations/topological_sort.py

    diff --git a/django/db/migrations/topological_sort.py b/django/db/migrations/topological_sort.py
    index 7b1ec7c..e0a22c9 100644
    a b def topological_sort_as_sets(dependency_graph):  
    1010    """
    1111    todo = dependency_graph.copy()
    1212    while todo:
    13         current = {node for node, deps in todo.items() if len(deps) == 0}
     13        current = {node for node, deps in todo.items() if not deps}
    1414
    1515        if not current:
    1616            raise ValueError('Cyclic dependency in graph: {}'.format(
  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index 09e5b62..0b44d4d 100644
    a b class Model(metaclass=ModelBase):  
    583583        of the field will call this method.
    584584        """
    585585        if fields is not None:
    586             if len(fields) == 0:
     586            if not fields:
    587587                return
    588588            if any(LOOKUP_SEP in f for f in fields):
    589589                raise ValueError(
    class Model(metaclass=ModelBase):  
    688688            # If update_fields is empty, skip the save. We do also check for
    689689            # no-op saves later on for inheritance cases. This bailout is
    690690            # still needed for skipping signal sending.
    691             if len(update_fields) == 0:
     691            if not update_fields:
    692692                return
    693693
    694694            update_fields = frozenset(update_fields)
  • django/db/models/expressions.py

    diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
    index dadbce6..ae41bfc 100644
    a b class ExpressionList(Func):  
    780780    template = '%(expressions)s'
    781781
    782782    def __init__(self, *expressions, **extra):
    783         if len(expressions) == 0:
     783        if not expressions:
    784784            raise ValueError('%s requires at least one expression.' % self.__class__.__name__)
    785785        super().__init__(*expressions, **extra)
    786786
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 2ffbc67..c3a3cf9 100644
    a b class ForeignObject(RelatedField):  
    600600        return name, path, args, kwargs
    601601
    602602    def resolve_related_fields(self):
    603         if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
     603        if not self.from_fields or len(self.from_fields) != len(self.to_fields):
    604604            raise ValueError('Foreign Object from and to fields must be the same non-zero length')
    605605        if isinstance(self.remote_field.model, str):
    606606            raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
    class ManyToManyField(RelatedField):  
    11611161                )
    11621162            )
    11631163
    1164         if len(self._validators) > 0:
     1164        if self._validators:
    11651165            warnings.append(
    11661166                checks.Warning(
    11671167                    'ManyToManyField does not support validators.',
  • django/db/models/query.py

    diff --git a/django/db/models/query.py b/django/db/models/query.py
    index 9261f73..be7c5ba 100644
    a b def prefetch_related_objects(model_instances, *related_lookups):  
    14401440    Populate prefetched object caches for a list of model instances based on
    14411441    the lookups/Prefetch instances given.
    14421442    """
    1443     if len(model_instances) == 0:
     1443    if not model_instances:
    14441444        return  # nothing to do
    14451445
    14461446    # We need to be able to dynamically add to the list of prefetch_related
    def prefetch_related_objects(model_instances, *related_lookups):  
    14681468        through_attrs = lookup.prefetch_through.split(LOOKUP_SEP)
    14691469        for level, through_attr in enumerate(through_attrs):
    14701470            # Prepare main instances
    1471             if len(obj_list) == 0:
     1471            if not obj_list:
    14721472                break
    14731473
    14741474            prefetch_to = lookup.get_current_prefetch_to(level)
  • django/db/models/sql/query.py

    diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
    index 1e26d25..fb49352 100644
    a b class Query:  
    10611061        and get_transform().
    10621062        """
    10631063        # __exact is the default lookup if one isn't given.
    1064         if len(lookups) == 0:
     1064        if not lookups:
    10651065            lookups = ['exact']
    10661066
    10671067        for name in lookups[:-1]:
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 81ebd5f..3d0cb62 100644
    a b def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):  
    10061006                raise ValueError(
    10071007                    "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label)
    10081008                )
    1009         elif len(fks_to_parent) == 0:
     1009        elif not fks_to_parent:
    10101010            raise ValueError(
    10111011                "'%s' has no field named '%s'." % (model._meta.label, fk_name)
    10121012            )
    def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):  
    10211021        ]
    10221022        if len(fks_to_parent) == 1:
    10231023            fk = fks_to_parent[0]
    1024         elif len(fks_to_parent) == 0:
     1024        elif not fks_to_parent:
    10251025            if can_fail:
    10261026                return
    10271027            raise ValueError(
  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index d4bed68..c5f520b 100644
    a b def slice_filter(value, arg):  
    568568    try:
    569569        bits = []
    570570        for x in arg.split(':'):
    571             if len(x) == 0:
     571            if not x:
    572572                bits.append(None)
    573573            else:
    574574                bits.append(int(x))
  • django/template/defaulttags.py

    diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
    index a872ffd..54b98e4 100644
    a b def firstof(parser, token):  
    715715    """
    716716    bits = token.split_contents()[1:]
    717717    asvar = None
    718     if len(bits) < 1:
     718    if not bits:
    719719        raise TemplateSyntaxError("'firstof' statement requires at least one argument")
    720720
    721721    if len(bits) >= 2 and bits[-2] == 'as':
    def url(parser, token):  
    13631363        asvar = bits[-1]
    13641364        bits = bits[:-2]
    13651365
    1366     if len(bits):
     1366    if bits:
    13671367        for bit in bits:
    13681368            match = kwarg_re.match(bit)
    13691369            if not match:
  • django/test/testcases.py

    diff --git a/django/test/testcases.py b/django/test/testcases.py
    index 4c32c87..2b625ac 100644
    a b class _AssertTemplateUsedContext:  
    114114
    115115        if not self.test():
    116116            message = self.message()
    117             if len(self.rendered_templates) == 0:
    118                 message += ' No template was rendered.'
    119             else:
     117            if self.rendered_templates:
    120118                message += ' Following templates were rendered: %s' % (
    121119                    ', '.join(self.rendered_template_names))
     120            else:
     121                message += ' No template was rendered.'
    122122            self.test_case.fail(message)
    123123
    124124
    class SimpleTestCase(unittest.TestCase):  
    602602            kwargs: Extra kwargs.
    603603        """
    604604        callable_obj = None
    605         if len(args):
     605        if args:
    606606            callable_obj = args[0]
    607607            args = args[1:]
    608608
  • django/urls/resolvers.py

    diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py
    index b8a33aa..55785a6 100644
    a b class URLResolver:  
    379379        self._local = threading.local()
    380380
    381381    def __repr__(self):
    382         if isinstance(self.urlconf_name, list) and len(self.urlconf_name):
     382        if isinstance(self.urlconf_name, list) and self.urlconf_name:
    383383            # Don't bother to output the whole list, it can be huge
    384384            urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
    385385        else:
  • django/utils/text.py

    diff --git a/django/utils/text.py b/django/utils/text.py
    index 3e04f8b..e69f1e1 100644
    a b def get_text_list(list_, last_word=gettext_lazy('or')):  
    247247    >>> get_text_list([])
    248248    ''
    249249    """
    250     if len(list_) == 0:
     250    if not list_:
    251251        return ''
    252252    if len(list_) == 1:
    253253        return str(list_[0])
  • django/utils/translation/trans_real.py

    diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
    index c640c42..334e31c 100644
    a b def gettext(message):  
    304304
    305305    eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
    306306
    307     if len(eol_message) == 0:
    308         # Return an empty value of the corresponding type if an empty message
    309         # is given, instead of metadata, which is the default gettext behavior.
    310         result = type(message)("")
    311     else:
     307    if eol_message:
    312308        _default = _default or translation(settings.LANGUAGE_CODE)
    313309        translation_object = getattr(_active, "value", _default)
    314310
    315311        result = translation_object.gettext(eol_message)
     312    else:
     313        # Return an empty value of the corresponding type if an empty message
     314        # is given, instead of metadata, which is the default gettext behavior.
     315        result = type(message)("")
    316316
    317317    if isinstance(message, SafeData):
    318318        return mark_safe(result)
  • docs/_ext/djangodocs.py

    diff --git a/docs/_ext/djangodocs.py b/docs/_ext/djangodocs.py
    index 66e87cd..21abe99 100644
    a b class DjangoHTMLTranslator(HTMLTranslator):  
    277277        if version_text:
    278278            title = "%s%s" % (
    279279                version_text % node['version'],
    280                 ":" if len(node) else "."
     280                ":" if node else "."
    281281            )
    282282            self.body.append('<span class="title">%s</span> ' % title)
    283283
  • tests/migrations/test_autodetector.py

    diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
    index 95aeec5..a111b8f 100644
    a b class AutodetectorTests(TestCase):  
    11641164
    11651165        def test(from_state, to_state, msg):
    11661166            changes = self.get_changes([from_state], [to_state])
    1167             if len(changes) > 0:
     1167            if changes:
    11681168                ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations)
    11691169                self.fail('Created operation(s) %s from %s' % (ops, msg))
    11701170
Back to Top