-
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):
|
25 | 25 | f for f in obj.model._meta.private_fields |
26 | 26 | if isinstance(f, GenericForeignKey) |
27 | 27 | ] |
28 | | if len(gfks) == 0: |
| 28 | if not gfks: |
29 | 29 | return [ |
30 | 30 | checks.Error( |
31 | 31 | "'%s.%s' has no GenericForeignKey." % ( |
-
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):
|
74 | 74 | "['url_starts_with'] [for user] as context_name" % |
75 | 75 | {'tag_name': bits[0]}) |
76 | 76 | # Must have at 3-6 bits in the tag |
77 | | if len(bits) >= 3 and len(bits) <= 6: |
| 77 | if 3 <= len(bits) <= 6: |
78 | 78 | |
79 | 79 | # If there's an even number of bits, there's no prefix |
80 | 80 | if len(bits) % 2 == 0: |
-
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):
|
37 | 37 | |
38 | 38 | # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility] |
39 | 39 | if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): |
40 | | if len(init_holes[0]) == 0: |
| 40 | if not init_holes[0]: |
41 | 41 | init_holes = () |
42 | 42 | n_holes = 0 |
43 | 43 | elif isinstance(init_holes[0][0], LinearRing): |
-
diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py
index 77c060c..d6395e0 100644
a
|
b
|
class ManagementUtility:
|
351 | 351 | if subcommand == 'help': |
352 | 352 | if '--commands' in args: |
353 | 353 | sys.stdout.write(self.main_help_text(commands_only=True) + '\n') |
354 | | elif len(options.args) < 1: |
| 354 | elif not options.args: |
355 | 355 | sys.stdout.write(self.main_help_text() + '\n') |
356 | 356 | else: |
357 | 357 | self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0]) |
-
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):
|
33 | 33 | db = options['database'] |
34 | 34 | self.verbosity = options['verbosity'] |
35 | 35 | dry_run = options['dry_run'] |
36 | | if len(tablenames): |
| 36 | if tablenames: |
37 | 37 | # Legacy behavior, tablename specified as argument |
38 | 38 | for tablename in tablenames: |
39 | 39 | self.create_table(db, tablename, dry_run) |
-
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):
|
84 | 84 | |
85 | 85 | excluded_models, excluded_apps = parse_apps_and_model_labels(excludes) |
86 | 86 | |
87 | | if len(app_labels) == 0: |
| 87 | if not app_labels: |
88 | 88 | if primary_keys: |
89 | 89 | raise CommandError("You can only use --pks option with one model") |
90 | 90 | app_list = OrderedDict.fromkeys( |
-
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):
|
164 | 164 | if self.verbosity >= 1: |
165 | 165 | if len(app_labels) == 1: |
166 | 166 | self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) |
167 | | elif len(app_labels) > 1: |
| 167 | elif app_labels: |
168 | 168 | self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) |
169 | 169 | else: |
170 | 170 | self.stdout.write("No changes detected") |
-
diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
index ae77de5..b697758 100644
a
|
b
|
class FormatStylePlaceholderCursor:
|
476 | 476 | # Handle params as dict |
477 | 477 | args = {k: ":%s" % k for k in params} |
478 | 478 | query = query % args |
479 | | elif unify_by_values and len(params) > 0: |
| 479 | elif unify_by_values and params: |
480 | 480 | # Handle params as a dict with unified query parameters by their |
481 | 481 | # values. It can be used only in single query execute() because |
482 | 482 | # executemany() shares the formatted query with each of the params |
-
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):
|
132 | 132 | for sequence_info in sequences: |
133 | 133 | table_name = sequence_info['table'] |
134 | 134 | column_name = sequence_info['column'] |
135 | | if not (column_name and len(column_name) > 0): |
| 135 | if not column_name: |
136 | 136 | # This will be the case if it's an m2m using an autogenerated |
137 | 137 | # intermediate table (see BaseDatabaseIntrospection.sequence_list) |
138 | 138 | column_name = 'id' |
-
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
index a7e5949..b58e4fc 100644
a
|
b
|
class MigrationAutodetector:
|
1217 | 1217 | return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) |
1218 | 1218 | if isinstance(ops[0], operations.RemoveField): |
1219 | 1219 | return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) |
1220 | | elif len(ops) > 1: |
| 1220 | elif ops: |
1221 | 1221 | if all(isinstance(o, operations.CreateModel) for o in ops): |
1222 | 1222 | return "_".join(sorted(o.name_lower for o in ops)) |
1223 | 1223 | return "auto_%s" % get_migration_name_timestamp() |
-
diff --git a/django/db/migrations/graph.py b/django/db/migrations/graph.py
index 687a9b3..4bb66b7 100644
a
|
b
|
class MigrationGraph:
|
360 | 360 | """ |
361 | 361 | if nodes is None: |
362 | 362 | nodes = list(self.leaf_nodes()) |
363 | | if len(nodes) == 0: |
| 363 | if not nodes: |
364 | 364 | return ProjectState() |
365 | 365 | if not isinstance(nodes[0], tuple): |
366 | 366 | nodes = [nodes] |
-
diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py
index ae79777..beae84f 100644
a
|
b
|
class MigrationLoader:
|
133 | 133 | raise AmbiguityError( |
134 | 134 | "There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix) |
135 | 135 | ) |
136 | | if len(results) == 0: |
| 136 | if not results: |
137 | 137 | raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix)) |
138 | 138 | return self.disk_migrations[results[0]] |
139 | 139 | |
-
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):
|
10 | 10 | """ |
11 | 11 | todo = dependency_graph.copy() |
12 | 12 | 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} |
14 | 14 | |
15 | 15 | if not current: |
16 | 16 | raise ValueError('Cyclic dependency in graph: {}'.format( |
-
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 09e5b62..0b44d4d 100644
a
|
b
|
class Model(metaclass=ModelBase):
|
583 | 583 | of the field will call this method. |
584 | 584 | """ |
585 | 585 | if fields is not None: |
586 | | if len(fields) == 0: |
| 586 | if not fields: |
587 | 587 | return |
588 | 588 | if any(LOOKUP_SEP in f for f in fields): |
589 | 589 | raise ValueError( |
… |
… |
class Model(metaclass=ModelBase):
|
688 | 688 | # If update_fields is empty, skip the save. We do also check for |
689 | 689 | # no-op saves later on for inheritance cases. This bailout is |
690 | 690 | # still needed for skipping signal sending. |
691 | | if len(update_fields) == 0: |
| 691 | if not update_fields: |
692 | 692 | return |
693 | 693 | |
694 | 694 | update_fields = frozenset(update_fields) |
-
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index dadbce6..ae41bfc 100644
a
|
b
|
class ExpressionList(Func):
|
780 | 780 | template = '%(expressions)s' |
781 | 781 | |
782 | 782 | def __init__(self, *expressions, **extra): |
783 | | if len(expressions) == 0: |
| 783 | if not expressions: |
784 | 784 | raise ValueError('%s requires at least one expression.' % self.__class__.__name__) |
785 | 785 | super().__init__(*expressions, **extra) |
786 | 786 | |
-
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):
|
600 | 600 | return name, path, args, kwargs |
601 | 601 | |
602 | 602 | 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): |
604 | 604 | raise ValueError('Foreign Object from and to fields must be the same non-zero length') |
605 | 605 | if isinstance(self.remote_field.model, str): |
606 | 606 | raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) |
… |
… |
class ManyToManyField(RelatedField):
|
1161 | 1161 | ) |
1162 | 1162 | ) |
1163 | 1163 | |
1164 | | if len(self._validators) > 0: |
| 1164 | if self._validators: |
1165 | 1165 | warnings.append( |
1166 | 1166 | checks.Warning( |
1167 | 1167 | 'ManyToManyField does not support validators.', |
-
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):
|
1440 | 1440 | Populate prefetched object caches for a list of model instances based on |
1441 | 1441 | the lookups/Prefetch instances given. |
1442 | 1442 | """ |
1443 | | if len(model_instances) == 0: |
| 1443 | if not model_instances: |
1444 | 1444 | return # nothing to do |
1445 | 1445 | |
1446 | 1446 | # We need to be able to dynamically add to the list of prefetch_related |
… |
… |
def prefetch_related_objects(model_instances, *related_lookups):
|
1468 | 1468 | through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) |
1469 | 1469 | for level, through_attr in enumerate(through_attrs): |
1470 | 1470 | # Prepare main instances |
1471 | | if len(obj_list) == 0: |
| 1471 | if not obj_list: |
1472 | 1472 | break |
1473 | 1473 | |
1474 | 1474 | prefetch_to = lookup.get_current_prefetch_to(level) |
-
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 1e26d25..fb49352 100644
a
|
b
|
class Query:
|
1061 | 1061 | and get_transform(). |
1062 | 1062 | """ |
1063 | 1063 | # __exact is the default lookup if one isn't given. |
1064 | | if len(lookups) == 0: |
| 1064 | if not lookups: |
1065 | 1065 | lookups = ['exact'] |
1066 | 1066 | |
1067 | 1067 | for name in lookups[:-1]: |
-
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):
|
1006 | 1006 | raise ValueError( |
1007 | 1007 | "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label) |
1008 | 1008 | ) |
1009 | | elif len(fks_to_parent) == 0: |
| 1009 | elif not fks_to_parent: |
1010 | 1010 | raise ValueError( |
1011 | 1011 | "'%s' has no field named '%s'." % (model._meta.label, fk_name) |
1012 | 1012 | ) |
… |
… |
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
|
1021 | 1021 | ] |
1022 | 1022 | if len(fks_to_parent) == 1: |
1023 | 1023 | fk = fks_to_parent[0] |
1024 | | elif len(fks_to_parent) == 0: |
| 1024 | elif not fks_to_parent: |
1025 | 1025 | if can_fail: |
1026 | 1026 | return |
1027 | 1027 | raise ValueError( |
-
diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index d4bed68..c5f520b 100644
a
|
b
|
def slice_filter(value, arg):
|
568 | 568 | try: |
569 | 569 | bits = [] |
570 | 570 | for x in arg.split(':'): |
571 | | if len(x) == 0: |
| 571 | if not x: |
572 | 572 | bits.append(None) |
573 | 573 | else: |
574 | 574 | bits.append(int(x)) |
-
diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
index a872ffd..54b98e4 100644
a
|
b
|
def firstof(parser, token):
|
715 | 715 | """ |
716 | 716 | bits = token.split_contents()[1:] |
717 | 717 | asvar = None |
718 | | if len(bits) < 1: |
| 718 | if not bits: |
719 | 719 | raise TemplateSyntaxError("'firstof' statement requires at least one argument") |
720 | 720 | |
721 | 721 | if len(bits) >= 2 and bits[-2] == 'as': |
… |
… |
def url(parser, token):
|
1363 | 1363 | asvar = bits[-1] |
1364 | 1364 | bits = bits[:-2] |
1365 | 1365 | |
1366 | | if len(bits): |
| 1366 | if bits: |
1367 | 1367 | for bit in bits: |
1368 | 1368 | match = kwarg_re.match(bit) |
1369 | 1369 | if not match: |
-
diff --git a/django/test/testcases.py b/django/test/testcases.py
index 4c32c87..2b625ac 100644
a
|
b
|
class _AssertTemplateUsedContext:
|
114 | 114 | |
115 | 115 | if not self.test(): |
116 | 116 | message = self.message() |
117 | | if len(self.rendered_templates) == 0: |
118 | | message += ' No template was rendered.' |
119 | | else: |
| 117 | if self.rendered_templates: |
120 | 118 | message += ' Following templates were rendered: %s' % ( |
121 | 119 | ', '.join(self.rendered_template_names)) |
| 120 | else: |
| 121 | message += ' No template was rendered.' |
122 | 122 | self.test_case.fail(message) |
123 | 123 | |
124 | 124 | |
… |
… |
class SimpleTestCase(unittest.TestCase):
|
602 | 602 | kwargs: Extra kwargs. |
603 | 603 | """ |
604 | 604 | callable_obj = None |
605 | | if len(args): |
| 605 | if args: |
606 | 606 | callable_obj = args[0] |
607 | 607 | args = args[1:] |
608 | 608 | |
-
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py
index b8a33aa..55785a6 100644
a
|
b
|
class URLResolver:
|
379 | 379 | self._local = threading.local() |
380 | 380 | |
381 | 381 | 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: |
383 | 383 | # Don't bother to output the whole list, it can be huge |
384 | 384 | urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__ |
385 | 385 | else: |
-
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')):
|
247 | 247 | >>> get_text_list([]) |
248 | 248 | '' |
249 | 249 | """ |
250 | | if len(list_) == 0: |
| 250 | if not list_: |
251 | 251 | return '' |
252 | 252 | if len(list_) == 1: |
253 | 253 | return str(list_[0]) |
-
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):
|
304 | 304 | |
305 | 305 | eol_message = message.replace('\r\n', '\n').replace('\r', '\n') |
306 | 306 | |
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: |
312 | 308 | _default = _default or translation(settings.LANGUAGE_CODE) |
313 | 309 | translation_object = getattr(_active, "value", _default) |
314 | 310 | |
315 | 311 | 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)("") |
316 | 316 | |
317 | 317 | if isinstance(message, SafeData): |
318 | 318 | return mark_safe(result) |
-
diff --git a/docs/_ext/djangodocs.py b/docs/_ext/djangodocs.py
index 66e87cd..21abe99 100644
a
|
b
|
class DjangoHTMLTranslator(HTMLTranslator):
|
277 | 277 | if version_text: |
278 | 278 | title = "%s%s" % ( |
279 | 279 | version_text % node['version'], |
280 | | ":" if len(node) else "." |
| 280 | ":" if node else "." |
281 | 281 | ) |
282 | 282 | self.body.append('<span class="title">%s</span> ' % title) |
283 | 283 | |
-
diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
index 95aeec5..a111b8f 100644
a
|
b
|
class AutodetectorTests(TestCase):
|
1164 | 1164 | |
1165 | 1165 | def test(from_state, to_state, msg): |
1166 | 1166 | changes = self.get_changes([from_state], [to_state]) |
1167 | | if len(changes) > 0: |
| 1167 | if changes: |
1168 | 1168 | ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations) |
1169 | 1169 | self.fail('Created operation(s) %s from %s' % (ops, msg)) |
1170 | 1170 | |