Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Replaced an antiquated pattern.

Thanks Lennart Regebro for pointing it out.
  • Loading branch information...
commit 9c487b5974ee7e7f196079611d7352364e8873ed 1 parent b1bfd96
Aymeric Augustin authored May 17, 2013

Showing 30 changed files with 49 additions and 43 deletions. Show diff stats Hide diff stats

  1. 4  django/contrib/admin/options.py
  2. 2  django/contrib/comments/views/utils.py
  3. 2  django/contrib/contenttypes/views.py
  4. 2  django/contrib/formtools/tests/wizard/test_forms.py
  5. 2  django/contrib/gis/sitemaps/views.py
  6. 2  django/contrib/gis/utils/layermapping.py
  7. 2  django/contrib/staticfiles/management/commands/collectstatic.py
  8. 2  django/core/management/__init__.py
  9. 4  django/core/management/base.py
  10. 2  django/core/management/commands/createcachetable.py
  11. 4  django/core/management/commands/runserver.py
  12. 10  django/db/models/base.py
  13. 4  django/db/models/fields/__init__.py
  14. 2  django/db/models/options.py
  15. 2  django/db/models/related.py
  16. 4  django/db/models/sql/aggregates.py
  17. 8  django/db/models/sql/compiler.py
  18. 2  django/db/models/sql/query.py
  19. 2  django/db/models/sql/subqueries.py
  20. 2  django/forms/forms.py
  21. 2  django/forms/formsets.py
  22. 2  django/forms/widgets.py
  23. 2  django/http/multipartparser.py
  24. 2  django/template/base.py
  25. 4  django/template/defaulttags.py
  26. 2  django/utils/dateformat.py
  27. 5  django/utils/html.py
  28. 2  django/utils/log.py
  29. 5  django/utils/translation/trans_real.py
  30. 2  django/utils/tree.py
4  django/contrib/admin/options.py
@@ -37,7 +37,7 @@
37 37
 
38 38
 HORIZONTAL, VERTICAL = 1, 2
39 39
 # returns the <ul> class for a given radio_admin field
40  
-get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
  40
+get_ul_class = lambda x: 'radiolist%s' % (' inline' if x == HORIZONTAL else '')
41 41
 
42 42
 
43 43
 class IncorrectLookupParameters(Exception):
@@ -189,7 +189,7 @@ def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
189 189
             kwargs['widget'] = widgets.AdminRadioSelect(attrs={
190 190
                 'class': get_ul_class(self.radio_fields[db_field.name]),
191 191
             })
192  
-            kwargs['empty_label'] = db_field.blank and _('None') or None
  192
+            kwargs['empty_label'] = _('None') if db_field.blank else None
193 193
 
194 194
         queryset = self.get_field_queryset(db, db_field, request)
195 195
         if queryset is not None:
2  django/contrib/comments/views/utils.py
@@ -37,7 +37,7 @@ def next_redirect(request, fallback, **get_kwargs):
37 37
         else:
38 38
             anchor = ''
39 39
 
40  
-        joiner = ('?' in next) and '&' or '?'
  40
+        joiner = '&' if '?' in next else '?'
41 41
         next += joiner + urlencode(get_kwargs) + anchor
42 42
     return HttpResponseRedirect(next)
43 43
 
2  django/contrib/contenttypes/views.py
@@ -75,7 +75,7 @@ def shortcut(request, content_type_id, object_id):
75 75
     # If all that malarkey found an object domain, use it. Otherwise, fall back
76 76
     # to whatever get_absolute_url() returned.
77 77
     if object_domain is not None:
78  
-        protocol = request.is_secure() and 'https' or 'http'
  78
+        protocol = 'https' if request.is_secure() else 'http'
79 79
         return http.HttpResponseRedirect('%s://%s%s'
80 80
                                          % (protocol, object_domain, absurl))
81 81
     else:
2  django/contrib/formtools/tests/wizard/test_forms.py
@@ -17,7 +17,7 @@
17 17
 class DummyRequest(http.HttpRequest):
18 18
     def __init__(self, POST=None):
19 19
         super(DummyRequest, self).__init__()
20  
-        self.method = POST and "POST" or "GET"
  20
+        self.method = "POST" if POST else "GET"
21 21
         if POST is not None:
22 22
             self.POST.update(POST)
23 23
         self.session = {}
2  django/contrib/gis/sitemaps/views.py
@@ -20,7 +20,7 @@ def index(request, sitemaps):
20 20
     """
21 21
     current_site = get_current_site(request)
22 22
     sites = []
23  
-    protocol = request.is_secure() and 'https' or 'http'
  23
+    protocol = 'https' if request.is_secure() else 'http'
24 24
     for section, site in sitemaps.items():
25 25
         if callable(site):
26 26
             pages = site().paginator.num_pages
2  django/contrib/gis/utils/layermapping.py
@@ -201,7 +201,7 @@ def check_ogr_fld(ogr_map_fld):
201 201
                 if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)):
202 202
                     raise LayerMapError('Invalid mapping geometry; model has %s%s, '
203 203
                                         'layer geometry type is %s.' %
204  
-                                        (fld_name, (coord_dim == 3 and '(dim=3)') or '', ltype))
  204
+                                        (fld_name, '(dim=3)' if coord_dim == 3 else '', ltype))
205 205
 
206 206
                 # Setting the `geom_field` attribute w/the name of the model field
207 207
                 # that is a Geometry.  Also setting the coordinate dimension
2  django/contrib/staticfiles/management/commands/collectstatic.py
@@ -174,7 +174,7 @@ def handle_noargs(self, **options):
174 174
                         "%(destination)s%(unmodified)s%(post_processed)s.\n")
175 175
             summary = template % {
176 176
                 'modified_count': modified_count,
177  
-                'identifier': 'static file' + (modified_count != 1 and 's' or ''),
  177
+                'identifier': 'static file' + ('' if modified_count == 1 else 's'),
178 178
                 'action': self.symlink and 'symlinked' or 'copied',
179 179
                 'destination': (destination_path and " to '%s'"
180 180
                                 % destination_path or ''),
2  django/core/management/__init__.py
@@ -63,7 +63,7 @@ def find_management_module(app_name):
63 63
 
64 64
     while parts:
65 65
         part = parts.pop()
66  
-        f, path, descr = imp.find_module(part, path and [path] or None)
  66
+        f, path, descr = imp.find_module(part, [path] if path else None)
67 67
         if f:
68 68
             f.close()
69 69
     return path
4  django/core/management/base.py
@@ -60,7 +60,7 @@ def __getattr__(self, name):
60 60
         return getattr(self._out, name)
61 61
 
62 62
     def write(self, msg, style_func=None, ending=None):
63  
-        ending = ending is None and self.ending or ending
  63
+        ending = self.ending if ending is None else ending
64 64
         if ending and not msg.endswith(ending):
65 65
             msg += ending
66 66
         style_func = [f for f in (style_func, self.style_func, lambda x:x)
@@ -311,7 +311,7 @@ def validate(self, app=None, display_num_errors=False):
311 311
             error_text = s.read()
312 312
             raise CommandError("One or more models did not validate:\n%s" % error_text)
313 313
         if display_num_errors:
314  
-            self.stdout.write("%s error%s found" % (num_errors, num_errors != 1 and 's' or ''))
  314
+            self.stdout.write("%s error%s found" % (num_errors, '' if num_errors == 1 else 's'))
315 315
 
316 316
     def handle(self, *args, **options):
317 317
         """
2  django/core/management/commands/createcachetable.py
@@ -44,7 +44,7 @@ def handle_label(self, tablename, **options):
44 44
             elif f.unique:
45 45
                 field_output.append("UNIQUE")
46 46
             if f.db_index:
47  
-                unique = f.unique and "UNIQUE " or ""
  47
+                unique = "UNIQUE " if f.unique else ""
48 48
                 index_output.append("CREATE %sINDEX %s ON %s (%s);" % \
49 49
                     (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename),
50 50
                     qn(f.name)))
4  django/core/management/commands/runserver.py
@@ -65,7 +65,7 @@ def handle(self, addrport='', *args, **options):
65 65
                 elif self.use_ipv6 and not _fqdn:
66 66
                     raise CommandError('"%s" is not a valid IPv6 address.' % self.addr)
67 67
         if not self.addr:
68  
-            self.addr = self.use_ipv6 and '::1' or '127.0.0.1'
  68
+            self.addr = '::1' if self.use_ipv6 else '127.0.0.1'
69 69
             self._raw_ipv6 = bool(self.use_ipv6)
70 70
         self.run(*args, **options)
71 71
 
@@ -86,7 +86,7 @@ def inner_run(self, *args, **options):
86 86
 
87 87
         threading = options.get('use_threading')
88 88
         shutdown_message = options.get('shutdown_message', '')
89  
-        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
  89
+        quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
90 90
 
91 91
         self.stdout.write("Validating models...\n\n")
92 92
         self.validate(display_num_errors=True)
10  django/db/models/base.py
@@ -631,7 +631,7 @@ def _save_table(self, raw=False, cls=None, force_insert=False,
631 631
         # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
632 632
         if pk_set and not force_insert:
633 633
             base_qs = cls._base_manager.using(using)
634  
-            values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False)))
  634
+            values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
635 635
                       for f in non_pks]
636 636
             if not values:
637 637
                 # We can end up here when saving a model in inheritance chain where
@@ -698,8 +698,8 @@ def _get_FIELD_display(self, field):
698 698
     def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
699 699
         if not self.pk:
700 700
             raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
701  
-        op = is_next and 'gt' or 'lt'
702  
-        order = not is_next and '-' or ''
  701
+        op = 'gt' if is_next else 'lt'
  702
+        order = '' if is_next else '-'
703 703
         param = force_text(getattr(self, field.attname))
704 704
         q = Q(**{'%s__%s' % (field.name, op): param})
705 705
         q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk})
@@ -712,8 +712,8 @@ def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
712 712
     def _get_next_or_previous_in_order(self, is_next):
713 713
         cachename = "__%s_order_cache" % is_next
714 714
         if not hasattr(self, cachename):
715  
-            op = is_next and 'gt' or 'lt'
716  
-            order = not is_next and '-_order' or '_order'
  715
+            op = 'gt' if is_next else 'lt'
  716
+            order = '_order' if is_next else '-_order'
717 717
             order_field = self._meta.order_with_respect_to
718 718
             obj = self._default_manager.filter(**{
719 719
                 order_field.name: getattr(self, order_field.attname)
4  django/db/models/fields/__init__.py
@@ -448,7 +448,7 @@ def get_validator_unique_lookup_type(self):
448 448
     def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
449 449
         """Returns choices with a default blank choices included, for use
450 450
         as SelectField choices for this field."""
451  
-        first_choice = include_blank and blank_choice or []
  451
+        first_choice = blank_choice if include_blank else []
452 452
         if self.choices:
453 453
             return first_choice + list(self.choices)
454 454
         rel_model = self.rel.to
@@ -471,7 +471,7 @@ def get_flatchoices(self, include_blank=True,
471 471
         """
472 472
         Returns flattened choices with a default blank choice included.
473 473
         """
474  
-        first_choice = include_blank and blank_choice or []
  474
+        first_choice = blank_choice if include_blank else []
475 475
         return first_choice + list(self.flatchoices)
476 476
 
477 477
     def _get_val_from_obj(self, obj):
2  django/db/models/options.py
@@ -347,7 +347,7 @@ def get_field(self, name, many_to_many=True):
347 347
         """
348 348
         Returns the requested field by name. Raises FieldDoesNotExist on error.
349 349
         """
350  
-        to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
  350
+        to_search = (self.fields + self.many_to_many) if many_to_many else self.fields
351 351
         for f in to_search:
352 352
             if f.name == name:
353 353
                 return f
2  django/db/models/related.py
@@ -27,7 +27,7 @@ def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH,
4  django/db/models/sql/aggregates.py
@@ -112,7 +112,7 @@ class StdDev(Aggregate):
112 112
 
113 113
     def __init__(self, col, sample=False, **extra):
114 114
         super(StdDev, self).__init__(col, **extra)
115  
-        self.sql_function = sample and 'STDDEV_SAMP' or 'STDDEV_POP'
  115
+        self.sql_function = 'STDDEV_SAMP' if sample else 'STDDEV_POP'
116 116
 
117 117
 class Sum(Aggregate):
118 118
     sql_function = 'SUM'
@@ -122,4 +122,4 @@ class Variance(Aggregate):
122 122
 
123 123
     def __init__(self, col, sample=False, **extra):
124 124
         super(Variance, self).__init__(col, **extra)
125  
-        self.sql_function = sample and 'VAR_SAMP' or 'VAR_POP'
  125
+        self.sql_function = 'VAR_SAMP' if sample else 'VAR_POP'
8  django/db/models/sql/compiler.py
@@ -512,7 +512,7 @@ def get_from_clause(self):
512 512
                 # Extra tables can end up in self.tables, but not in the
513 513
                 # alias_map if they aren't in a join. That's OK. We skip them.
514 514
                 continue
515  
-            alias_str = (alias != name and ' %s' % alias or '')
  515
+            alias_str = '' if alias == name else (' %s' % alias)
516 516
             if join_type and not first:
517 517
                 extra_cond = join_field.get_extra_restriction(
518 518
                     self.query.where_class, alias, lhs)
@@ -532,7 +532,7 @@ def get_from_clause(self):
532 532
                     (qn(lhs), qn2(lhs_col), qn(alias), qn2(rhs_col)))
533 533
                 result.append('%s)' % extra_sql)
534 534
             else:
535  
-                connector = not first and ', ' or ''
  535
+                connector = '' if first else ', '
536 536
                 result.append('%s%s%s' % (connector, qn(name), alias_str))
537 537
             first = False
538 538
         for t in self.query.extra_tables:
@@ -541,7 +541,7 @@ def get_from_clause(self):
541 541
             # calls increments the refcount, so an alias refcount of one means
542 542
             # this is the only reference.
543 543
             if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
544  
-                connector = not first and ', ' or ''
  544
+                connector = '' if first else ', '
545 545
                 result.append('%s%s' % (connector, qn(alias)))
546 546
                 first = False
547 547
         return result, from_params
@@ -959,7 +959,7 @@ def execute_sql(self, result_type):
959 959
         related queries are not available.
960 960
         """
961 961
         cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
962  
-        rows = cursor and cursor.rowcount or 0
  962
+        rows = cursor.rowcount if cursor else 0
963 963
         is_empty = cursor is None
964 964
         del cursor
965 965
         for query in self.query.get_related_updates():
2  django/db/models/sql/query.py
@@ -532,7 +532,7 @@ def combine(self, rhs, connector):
532 532
 
533 533
         # Ordering uses the 'rhs' ordering, unless it has none, in which case
534 534
         # the current ordering is used.
535  
-        self.order_by = rhs.order_by and rhs.order_by[:] or self.order_by
  535
+        self.order_by = rhs.order_by[:] if rhs.order_by else self.order_by
536 536
         self.extra_order_by = rhs.extra_order_by or self.extra_order_by
537 537
 
538 538
     def deferred_to_data(self, target, callback):
2  django/db/models/sql/subqueries.py
@@ -245,7 +245,7 @@ def add_select(self, field_name, lookup_type, order='ASC'):
245 245
         self.clear_select_clause()
246 246
         self.select = [SelectInfo(select, None)]
247 247
         self.distinct = True
248  
-        self.order_by = order == 'ASC' and [1] or [-1]
  248
+        self.order_by = [1] if order == 'ASC' else [-1]
249 249
 
250 250
         if field.null:
251 251
             self.add_filter(("%s__isnull" % field_name, False))
2  django/forms/forms.py
@@ -523,7 +523,7 @@ def label_tag(self, contents=None, attrs=None):
523 523
         widget = self.field.widget
524 524
         id_ = widget.attrs.get('id') or self.auto_id
525 525
         if id_:
526  
-            attrs = attrs and flatatt(attrs) or ''
  526
+            attrs = flatatt(attrs) if attrs else ''
527 527
             contents = format_html('<label for="{0}"{1}>{2}</label>',
528 528
                                    widget.id_for_label(id_), attrs, contents
529 529
                                    )
2  django/forms/formsets.py
@@ -119,7 +119,7 @@ def initial_form_count(self):
119 119
             return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
120 120
         else:
121 121
             # Use the length of the initial data if it's there, 0 otherwise.
122  
-            initial_forms = self.initial and len(self.initial) or 0
  122
+            initial_forms = len(self.initial) if self.initial else 0
123 123
         return initial_forms
124 124
 
125 125
     def _construct_forms(self):
2  django/forms/widgets.py
@@ -775,7 +775,7 @@ class MultiWidget(Widget):
775 775
     You'll probably want to use this class with MultiValueField.
776 776
     """
777 777
     def __init__(self, widgets, attrs=None):
778  
-        self.widgets = [isinstance(w, type) and w() or w for w in widgets]
  778
+        self.widgets = [w() if isinstance(w, type) else w for w in widgets]
779 779
         super(MultiWidget, self).__init__(attrs)
780 780
 
781 781
     def render(self, name, value, attrs=None):
2  django/http/multipartparser.py
@@ -292,7 +292,7 @@ def tell(self):
292 292
 
293 293
     def read(self, size=None):
294 294
         def parts():
295  
-            remaining = (size is not None and [size] or [self._remaining])[0]
  295
+            remaining = self._remaining if size is None else size
296 296
             # do the whole thing in one shot if no limit was provided.
297 297
             if remaining is None:
298 298
                 yield b''.join(self)
2  django/template/base.py
@@ -641,7 +641,7 @@ def args_check(name, func, provided):
641 641
                                       (name, len(nondefs), plen))
642 642
 
643 643
         # Defaults can be overridden.
644  
-        defaults = defaults and list(defaults) or []
  644
+        defaults = list(defaults) if defaults else []
645 645
         try:
646 646
             for parg in provided:
647 647
                 defaults.pop(0)
4  django/template/defaulttags.py
@@ -127,7 +127,7 @@ def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empt
127 127
             self.nodelist_empty = nodelist_empty
128 128
 
129 129
     def __repr__(self):
130  
-        reversed_text = self.is_reversed and ' reversed' or ''
  130
+        reversed_text = ' reversed' if self.is_reversed else ''
131 131
         return "<For Node: for %s in %s, tail_len: %d%s>" % \
132 132
             (', '.join(self.loopvars), self.sequence, len(self.nodelist_loop),
133 133
              reversed_text)
@@ -788,7 +788,7 @@ def do_for(parser, token):
788 788
                                   " words: %s" % token.contents)
789 789
 
790 790
     is_reversed = bits[-1] == 'reversed'
791  
-    in_index = is_reversed and -3 or -2
  791
+    in_index = -3 if is_reversed else -2
792 792
     if bits[in_index] != 'in':
793 793
         raise TemplateSyntaxError("'for' statements should use the format"
794 794
                                   " 'for x in y': %s" % token.contents)
2  django/utils/dateformat.py
@@ -234,7 +234,7 @@ def t(self):
234 234
 
235 235
     def T(self):
236 236
         "Time zone of this machine; e.g. 'EST' or 'MDT'"
237  
-        name = self.timezone and self.timezone.tzname(self.data) or None
  237
+        name = self.timezone.tzname(self.data) if self.timezone else None
238 238
         if name is None:
239 239
             name = self.format('O')
240 240
         return six.text_type(name)
5  django/utils/html.py
@@ -187,7 +187,10 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
187 187
 
188 188
     If autoescape is True, the link text and URLs will get autoescaped.
189 189
     """
190  
-    trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
  190
+    def trim_url(x, limit=trim_url_limit):
  191
+        if limit is None or len(x) <= limit:
  192
+            return x
  193
+        return '%s...' % x[:max(0, limit - 3)]
191 194
     safe_input = isinstance(text, SafeData)
192 195
     words = word_split_re.split(force_text(text))
193 196
     for i, word in enumerate(words):
2  django/utils/log.py
@@ -111,7 +111,7 @@ def emit(self, record):
111 111
 
112 112
         message = "%s\n\n%s" % (stack_trace, request_repr)
113 113
         reporter = ExceptionReporter(request, is_email=True, *exc_info)
114  
-        html_message = self.include_html and reporter.get_traceback_html() or None
  114
+        html_message = reporter.get_traceback_html() if self.include_html else None
115 115
         mail.mail_admins(subject, message, fail_silently=True,
116 116
                          html_message=html_message,
117 117
                          connection=self.connection())
5  django/utils/translation/trans_real.py
@@ -651,7 +651,10 @@ def parse_accept_lang_header(lang_string):
651 651
         first, lang, priority = pieces[i : i + 3]
652 652
         if first:
653 653
             return []
654  
-        priority = priority and float(priority) or 1.0
  654
+        if priority:
  655
+            priority = float(priority)
  656
+        if not priority:        # if priority is 0.0 at this point make it 1.0
  657
+             priority = 1.0
655 658
         result.append((lang, priority))
656 659
     result.sort(key=lambda k: k[1], reverse=True)
657 660
     return result
2  django/utils/tree.py
@@ -20,7 +20,7 @@ def __init__(self, children=None, connector=None, negated=False):
20 20
         Constructs a new Node. If no connector is given, the default will be
21 21
         used.
22 22
         """
23  
-        self.children = children and children[:] or []
  23
+        self.children = children[:] if children else []
24 24
         self.connector = connector or self.default
25 25
         self.negated = negated
26 26
 

0 notes on commit 9c487b5

Please sign in to comment.
Something went wrong with that request. Please try again.