diff options
| author | Aymeric Augustin <aymeric.augustin@m4x.org> | 2013-05-17 16:33:36 +0200 |
|---|---|---|
| committer | Aymeric Augustin <aymeric.augustin@m4x.org> | 2013-05-17 18:08:58 +0200 |
| commit | 9c487b5974ee7e7f196079611d7352364e8873ed (patch) | |
| tree | efc6ffa38da07b4302e145c33047cf2c41da105a /django | |
| parent | b1bfd9630ef049070b0cd6ae215470d3d1facd40 (diff) | |
Replaced an antiquated pattern.
Thanks Lennart Regebro for pointing it out.
Diffstat (limited to 'django')
30 files changed, 49 insertions, 43 deletions
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index 9bc3d55454..7373837bb0 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -37,7 +37,7 @@ from django.utils.encoding import force_text HORIZONTAL, VERTICAL = 1, 2 # returns the <ul> class for a given radio_admin field -get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') +get_ul_class = lambda x: 'radiolist%s' % (' inline' if x == HORIZONTAL else '') class IncorrectLookupParameters(Exception): @@ -189,7 +189,7 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)): kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) - kwargs['empty_label'] = db_field.blank and _('None') or None + kwargs['empty_label'] = _('None') if db_field.blank else None queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: diff --git a/django/contrib/comments/views/utils.py b/django/contrib/comments/views/utils.py index 79f6376232..da70272282 100644 --- a/django/contrib/comments/views/utils.py +++ b/django/contrib/comments/views/utils.py @@ -37,7 +37,7 @@ def next_redirect(request, fallback, **get_kwargs): else: anchor = '' - joiner = ('?' in next) and '&' or '?' + joiner = '&' if '?' in next else '?' next += joiner + urlencode(get_kwargs) + anchor return HttpResponseRedirect(next) diff --git a/django/contrib/contenttypes/views.py b/django/contrib/contenttypes/views.py index 5c22cb6672..6d4a719289 100644 --- a/django/contrib/contenttypes/views.py +++ b/django/contrib/contenttypes/views.py @@ -75,7 +75,7 @@ def shortcut(request, content_type_id, object_id): # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_url() returned. if object_domain is not None: - protocol = request.is_secure() and 'https' or 'http' + protocol = 'https' if request.is_secure() else 'http' return http.HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl)) else: diff --git a/django/contrib/formtools/tests/wizard/test_forms.py b/django/contrib/formtools/tests/wizard/test_forms.py index 7425755cf5..21917822a7 100644 --- a/django/contrib/formtools/tests/wizard/test_forms.py +++ b/django/contrib/formtools/tests/wizard/test_forms.py @@ -17,7 +17,7 @@ from django.contrib.formtools.wizard.views import (WizardView, class DummyRequest(http.HttpRequest): def __init__(self, POST=None): super(DummyRequest, self).__init__() - self.method = POST and "POST" or "GET" + self.method = "POST" if POST else "GET" if POST is not None: self.POST.update(POST) self.session = {} diff --git a/django/contrib/gis/sitemaps/views.py b/django/contrib/gis/sitemaps/views.py index 36e48f7d20..9682c125d2 100644 --- a/django/contrib/gis/sitemaps/views.py +++ b/django/contrib/gis/sitemaps/views.py @@ -20,7 +20,7 @@ def index(request, sitemaps): """ current_site = get_current_site(request) sites = [] - protocol = request.is_secure() and 'https' or 'http' + protocol = 'https' if request.is_secure() else 'http' for section, site in sitemaps.items(): if callable(site): pages = site().paginator.num_pages diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index 282dbc7450..cb56b8bce2 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -201,7 +201,7 @@ class LayerMapping(object): if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)): raise LayerMapError('Invalid mapping geometry; model has %s%s, ' 'layer geometry type is %s.' % - (fld_name, (coord_dim == 3 and '(dim=3)') or '', ltype)) + (fld_name, '(dim=3)' if coord_dim == 3 else '', ltype)) # Setting the `geom_field` attribute w/the name of the model field # that is a Geometry. Also setting the coordinate dimension diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py index 22fdac7c76..c620993f33 100644 --- a/django/contrib/staticfiles/management/commands/collectstatic.py +++ b/django/contrib/staticfiles/management/commands/collectstatic.py @@ -174,7 +174,7 @@ Type 'yes' to continue, or 'no' to cancel: """ "%(destination)s%(unmodified)s%(post_processed)s.\n") summary = template % { 'modified_count': modified_count, - 'identifier': 'static file' + (modified_count != 1 and 's' or ''), + 'identifier': 'static file' + ('' if modified_count == 1 else 's'), 'action': self.symlink and 'symlinked' or 'copied', 'destination': (destination_path and " to '%s'" % destination_path or ''), diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index 7638937c94..77d5e1b264 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -63,7 +63,7 @@ def find_management_module(app_name): while parts: part = parts.pop() - f, path, descr = imp.find_module(part, path and [path] or None) + f, path, descr = imp.find_module(part, [path] if path else None) if f: f.close() return path diff --git a/django/core/management/base.py b/django/core/management/base.py index e6a968bbad..ba6ad8f4c0 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -60,7 +60,7 @@ class OutputWrapper(object): return getattr(self._out, name) def write(self, msg, style_func=None, ending=None): - ending = ending is None and self.ending or ending + ending = self.ending if ending is None else ending if ending and not msg.endswith(ending): msg += ending style_func = [f for f in (style_func, self.style_func, lambda x:x) @@ -311,7 +311,7 @@ class BaseCommand(object): error_text = s.read() raise CommandError("One or more models did not validate:\n%s" % error_text) if display_num_errors: - self.stdout.write("%s error%s found" % (num_errors, num_errors != 1 and 's' or '')) + self.stdout.write("%s error%s found" % (num_errors, '' if num_errors == 1 else 's')) def handle(self, *args, **options): """ diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py index 94b6b09400..4d1bc0403e 100644 --- a/django/core/management/commands/createcachetable.py +++ b/django/core/management/commands/createcachetable.py @@ -44,7 +44,7 @@ class Command(LabelCommand): elif f.unique: field_output.append("UNIQUE") if f.db_index: - unique = f.unique and "UNIQUE " or "" + unique = "UNIQUE " if f.unique else "" index_output.append("CREATE %sINDEX %s ON %s (%s);" % \ (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename), qn(f.name))) diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py index 0ca15fdb6f..4fe03216d5 100644 --- a/django/core/management/commands/runserver.py +++ b/django/core/management/commands/runserver.py @@ -65,7 +65,7 @@ class Command(BaseCommand): elif self.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % self.addr) if not self.addr: - self.addr = self.use_ipv6 and '::1' or '127.0.0.1' + self.addr = '::1' if self.use_ipv6 else '127.0.0.1' self._raw_ipv6 = bool(self.use_ipv6) self.run(*args, **options) @@ -86,7 +86,7 @@ class Command(BaseCommand): threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') - quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' + quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Validating models...\n\n") self.validate(display_num_errors=True) diff --git a/django/db/models/base.py b/django/db/models/base.py index 1a8e32d49f..feea26b6cc 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -631,7 +631,7 @@ class Model(six.with_metaclass(ModelBase)): # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. if pk_set and not force_insert: base_qs = cls._base_manager.using(using) - values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) + values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) for f in non_pks] if not values: # We can end up here when saving a model in inheritance chain where @@ -698,8 +698,8 @@ class Model(six.with_metaclass(ModelBase)): def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): if not self.pk: raise ValueError("get_next/get_previous cannot be used on unsaved objects.") - op = is_next and 'gt' or 'lt' - order = not is_next and '-' or '' + op = 'gt' if is_next else 'lt' + order = '' if is_next else '-' param = force_text(getattr(self, field.attname)) q = Q(**{'%s__%s' % (field.name, op): param}) q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk}) @@ -712,8 +712,8 @@ class Model(six.with_metaclass(ModelBase)): def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next if not hasattr(self, cachename): - op = is_next and 'gt' or 'lt' - order = not is_next and '-_order' or '_order' + op = 'gt' if is_next else 'lt' + order = '_order' if is_next else '-_order' order_field = self._meta.order_with_respect_to obj = self._default_manager.filter(**{ order_field.name: getattr(self, order_field.attname) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index a925f0c577..13cec1bfba 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -448,7 +448,7 @@ class Field(object): def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): """Returns choices with a default blank choices included, for use as SelectField choices for this field.""" - first_choice = include_blank and blank_choice or [] + first_choice = blank_choice if include_blank else [] if self.choices: return first_choice + list(self.choices) rel_model = self.rel.to @@ -471,7 +471,7 @@ class Field(object): """ Returns flattened choices with a default blank choice included. """ - first_choice = include_blank and blank_choice or [] + first_choice = blank_choice if include_blank else [] return first_choice + list(self.flatchoices) def _get_val_from_obj(self, obj): diff --git a/django/db/models/options.py b/django/db/models/options.py index acb5ff38bc..b8a79023e8 100644 --- a/django/db/models/options.py +++ b/django/db/models/options.py @@ -347,7 +347,7 @@ class Options(object): """ Returns the requested field by name. Raises FieldDoesNotExist on error. """ - to_search = many_to_many and (self.fields + self.many_to_many) or self.fields + to_search = (self.fields + self.many_to_many) if many_to_many else self.fields for f in to_search: if f.name == name: return f diff --git a/django/db/models/related.py b/django/db/models/related.py index 6c93076c48..4b00dd343b 100644 --- a/django/db/models/related.py +++ b/django/db/models/related.py @@ -27,7 +27,7 @@ class RelatedObject(object): Analogue of django.db.models.fields.Field.get_choices, provided initially for utilisation by RelatedFieldListFilter. """ - first_choice = include_blank and blank_choice or [] + first_choice = blank_choice if include_blank else [] queryset = self.model._default_manager.all() if limit_to_currently_related: queryset = queryset.complex_filter( diff --git a/django/db/models/sql/aggregates.py b/django/db/models/sql/aggregates.py index 1b65847b7f..23b79923d1 100644 --- a/django/db/models/sql/aggregates.py +++ b/django/db/models/sql/aggregates.py @@ -112,7 +112,7 @@ class StdDev(Aggregate): def __init__(self, col, sample=False, **extra): super(StdDev, self).__init__(col, **extra) - self.sql_function = sample and 'STDDEV_SAMP' or 'STDDEV_POP' + self.sql_function = 'STDDEV_SAMP' if sample else 'STDDEV_POP' class Sum(Aggregate): sql_function = 'SUM' @@ -122,4 +122,4 @@ class Variance(Aggregate): def __init__(self, col, sample=False, **extra): super(Variance, self).__init__(col, **extra) - self.sql_function = sample and 'VAR_SAMP' or 'VAR_POP' + self.sql_function = 'VAR_SAMP' if sample else 'VAR_POP' diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 7b7c430420..bbe310c8c3 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -512,7 +512,7 @@ class SQLCompiler(object): # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue - alias_str = (alias != name and ' %s' % alias or '') + alias_str = '' if alias == name else (' %s' % alias) if join_type and not first: extra_cond = join_field.get_extra_restriction( self.query.where_class, alias, lhs) @@ -532,7 +532,7 @@ class SQLCompiler(object): (qn(lhs), qn2(lhs_col), qn(alias), qn2(rhs_col))) result.append('%s)' % extra_sql) else: - connector = not first and ', ' or '' + connector = '' if first else ', ' result.append('%s%s%s' % (connector, qn(name), alias_str)) first = False for t in self.query.extra_tables: @@ -541,7 +541,7 @@ class SQLCompiler(object): # calls increments the refcount, so an alias refcount of one means # this is the only reference. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1: - connector = not first and ', ' or '' + connector = '' if first else ', ' result.append('%s%s' % (connector, qn(alias))) first = False return result, from_params @@ -959,7 +959,7 @@ class SQLUpdateCompiler(SQLCompiler): related queries are not available. """ cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) - rows = cursor and cursor.rowcount or 0 + rows = cursor.rowcount if cursor else 0 is_empty = cursor is None del cursor for query in self.query.get_related_updates(): diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 6db2bf6e12..0a4152587d 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -532,7 +532,7 @@ class Query(object): # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. - self.order_by = rhs.order_by and rhs.order_by[:] or self.order_by + self.order_by = rhs.order_by[:] if rhs.order_by else self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def deferred_to_data(self, target, callback): diff --git a/django/db/models/sql/subqueries.py b/django/db/models/sql/subqueries.py index fae42b4be2..20770162c9 100644 --- a/django/db/models/sql/subqueries.py +++ b/django/db/models/sql/subqueries.py @@ -245,7 +245,7 @@ class DateQuery(Query): self.clear_select_clause() self.select = [SelectInfo(select, None)] self.distinct = True - self.order_by = order == 'ASC' and [1] or [-1] + self.order_by = [1] if order == 'ASC' else [-1] if field.null: self.add_filter(("%s__isnull" % field_name, False)) diff --git a/django/forms/forms.py b/django/forms/forms.py index f3a0fe6b38..b231de421a 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -523,7 +523,7 @@ class BoundField(object): widget = self.field.widget id_ = widget.attrs.get('id') or self.auto_id if id_: - attrs = attrs and flatatt(attrs) or '' + attrs = flatatt(attrs) if attrs else '' contents = format_html('<label for="{0}"{1}>{2}</label>', widget.id_for_label(id_), attrs, contents ) diff --git a/django/forms/formsets.py b/django/forms/formsets.py index 2bd11d9f53..d421770093 100644 --- a/django/forms/formsets.py +++ b/django/forms/formsets.py @@ -119,7 +119,7 @@ class BaseFormSet(object): return self.management_form.cleaned_data[INITIAL_FORM_COUNT] else: # Use the length of the initial data if it's there, 0 otherwise. - initial_forms = self.initial and len(self.initial) or 0 + initial_forms = len(self.initial) if self.initial else 0 return initial_forms def _construct_forms(self): diff --git a/django/forms/widgets.py b/django/forms/widgets.py index e72ab014b8..aca4a457af 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -775,7 +775,7 @@ class MultiWidget(Widget): You'll probably want to use this class with MultiValueField. """ def __init__(self, widgets, attrs=None): - self.widgets = [isinstance(w, type) and w() or w for w in widgets] + self.widgets = [w() if isinstance(w, type) else w for w in widgets] super(MultiWidget, self).__init__(attrs) def render(self, name, value, attrs=None): diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 0c07335f27..0e999f2ded 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -292,7 +292,7 @@ class LazyStream(six.Iterator): def read(self, size=None): def parts(): - remaining = (size is not None and [size] or [self._remaining])[0] + remaining = self._remaining if size is None else size # do the whole thing in one shot if no limit was provided. if remaining is None: yield b''.join(self) diff --git a/django/template/base.py b/django/template/base.py index c5bddaf63e..dc6b0c366c 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -641,7 +641,7 @@ class FilterExpression(object): (name, len(nondefs), plen)) # Defaults can be overridden. - defaults = defaults and list(defaults) or [] + defaults = list(defaults) if defaults else [] try: for parg in provided: defaults.pop(0) diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index b272322e1b..04e7a37d8e 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -127,7 +127,7 @@ class ForNode(Node): self.nodelist_empty = nodelist_empty def __repr__(self): - reversed_text = self.is_reversed and ' reversed' or '' + reversed_text = ' reversed' if self.is_reversed else '' return "<For Node: for %s in %s, tail_len: %d%s>" % \ (', '.join(self.loopvars), self.sequence, len(self.nodelist_loop), reversed_text) @@ -788,7 +788,7 @@ def do_for(parser, token): " words: %s" % token.contents) is_reversed = bits[-1] == 'reversed' - in_index = is_reversed and -3 or -2 + in_index = -3 if is_reversed else -2 if bits[in_index] != 'in': raise TemplateSyntaxError("'for' statements should use the format" " 'for x in y': %s" % token.contents) diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index b2586ba1ff..6d0a7b63f7 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -234,7 +234,7 @@ class DateFormat(TimeFormat): def T(self): "Time zone of this machine; e.g. 'EST' or 'MDT'" - name = self.timezone and self.timezone.tzname(self.data) or None + name = self.timezone.tzname(self.data) if self.timezone else None if name is None: name = self.format('O') return six.text_type(name) diff --git a/django/utils/html.py b/django/utils/html.py index 650e8485ab..8b28d97d13 100644 --- a/django/utils/html.py +++ b/django/utils/html.py @@ -187,7 +187,10 @@ def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): If autoescape is True, the link text and URLs will get autoescaped. """ - 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 + def trim_url(x, limit=trim_url_limit): + if limit is None or len(x) <= limit: + return x + return '%s...' % x[:max(0, limit - 3)] safe_input = isinstance(text, SafeData) words = word_split_re.split(force_text(text)) for i, word in enumerate(words): diff --git a/django/utils/log.py b/django/utils/log.py index b291b86706..a9b62caae1 100644 --- a/django/utils/log.py +++ b/django/utils/log.py @@ -111,7 +111,7 @@ class AdminEmailHandler(logging.Handler): message = "%s\n\n%s" % (stack_trace, request_repr) reporter = ExceptionReporter(request, is_email=True, *exc_info) - html_message = self.include_html and reporter.get_traceback_html() or None + html_message = reporter.get_traceback_html() if self.include_html else None mail.mail_admins(subject, message, fail_silently=True, html_message=html_message, connection=self.connection()) diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index ad172407de..07353c35ee 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -651,7 +651,10 @@ def parse_accept_lang_header(lang_string): first, lang, priority = pieces[i : i + 3] if first: return [] - priority = priority and float(priority) or 1.0 + if priority: + priority = float(priority) + if not priority: # if priority is 0.0 at this point make it 1.0 + priority = 1.0 result.append((lang, priority)) result.sort(key=lambda k: k[1], reverse=True) return result diff --git a/django/utils/tree.py b/django/utils/tree.py index 4152b4600b..3f93738b4f 100644 --- a/django/utils/tree.py +++ b/django/utils/tree.py @@ -20,7 +20,7 @@ class Node(object): Constructs a new Node. If no connector is given, the default will be used. """ - self.children = children and children[:] or [] + self.children = children[:] if children else [] self.connector = connector or self.default self.negated = negated |
