Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Replaced an antiquated pattern.

Thanks Lennart Regebro for pointing it out.
  • Loading branch information...
commit 9c487b5974ee7e7f196079611d7352364e8873ed 1 parent b1bfd96
@aaugustin aaugustin authored
Showing with 49 additions and 43 deletions.
  1. +2 −2 django/contrib/admin/options.py
  2. +1 −1  django/contrib/comments/views/utils.py
  3. +1 −1  django/contrib/contenttypes/views.py
  4. +1 −1  django/contrib/formtools/tests/wizard/test_forms.py
  5. +1 −1  django/contrib/gis/sitemaps/views.py
  6. +1 −1  django/contrib/gis/utils/layermapping.py
  7. +1 −1  django/contrib/staticfiles/management/commands/collectstatic.py
  8. +1 −1  django/core/management/__init__.py
  9. +2 −2 django/core/management/base.py
  10. +1 −1  django/core/management/commands/createcachetable.py
  11. +2 −2 django/core/management/commands/runserver.py
  12. +5 −5 django/db/models/base.py
  13. +2 −2 django/db/models/fields/__init__.py
  14. +1 −1  django/db/models/options.py
  15. +1 −1  django/db/models/related.py
  16. +2 −2 django/db/models/sql/aggregates.py
  17. +4 −4 django/db/models/sql/compiler.py
  18. +1 −1  django/db/models/sql/query.py
  19. +1 −1  django/db/models/sql/subqueries.py
  20. +1 −1  django/forms/forms.py
  21. +1 −1  django/forms/formsets.py
  22. +1 −1  django/forms/widgets.py
  23. +1 −1  django/http/multipartparser.py
  24. +1 −1  django/template/base.py
  25. +2 −2 django/template/defaulttags.py
  26. +1 −1  django/utils/dateformat.py
  27. +4 −1 django/utils/html.py
  28. +1 −1  django/utils/log.py
  29. +4 −1 django/utils/translation/trans_real.py
  30. +1 −1  django/utils/tree.py
View
4 django/contrib/admin/options.py
@@ -37,7 +37,7 @@
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 @@ def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
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:
View
2  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)
View
2  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:
View
2  django/contrib/formtools/tests/wizard/test_forms.py
@@ -17,7 +17,7 @@
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 = {}
View
2  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
View
2  django/contrib/gis/utils/layermapping.py
@@ -201,7 +201,7 @@ def check_ogr_fld(ogr_map_fld):
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
View
2  django/contrib/staticfiles/management/commands/collectstatic.py
@@ -174,7 +174,7 @@ def handle_noargs(self, **options):
"%(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 ''),
View
2  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
View
4 django/core/management/base.py
@@ -60,7 +60,7 @@ def __getattr__(self, name):
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 @@ def validate(self, app=None, display_num_errors=False):
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):
"""
View
2  django/core/management/commands/createcachetable.py
@@ -44,7 +44,7 @@ def handle_label(self, tablename, **options):
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)))
View
4 django/core/management/commands/runserver.py
@@ -65,7 +65,7 @@ def handle(self, addrport='', *args, **options):
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 @@ def inner_run(self, *args, **options):
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)
View
10 django/db/models/base.py
@@ -631,7 +631,7 @@ def _save_table(self, raw=False, cls=None, force_insert=False,
# 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 @@ def _get_FIELD_display(self, field):
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 @@ def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
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)
View
4 django/db/models/fields/__init__.py
@@ -448,7 +448,7 @@ def get_validator_unique_lookup_type(self):
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 @@ def get_flatchoices(self, include_blank=True,
"""
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):
View
2  django/db/models/options.py
@@ -347,7 +347,7 @@ def get_field(self, name, many_to_many=True):
"""
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
View
2  django/db/models/related.py
@@ -27,7 +27,7 @@ def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH,
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(
View
4 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'
View
8 django/db/models/sql/compiler.py
@@ -512,7 +512,7 @@ def get_from_clause(self):
# 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 @@ def get_from_clause(self):
(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 @@ def get_from_clause(self):
# 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 @@ def execute_sql(self, result_type):
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():
View
2  django/db/models/sql/query.py
@@ -532,7 +532,7 @@ def combine(self, rhs, connector):
# 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):
View
2  django/db/models/sql/subqueries.py
@@ -245,7 +245,7 @@ def add_select(self, field_name, lookup_type, order='ASC'):
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))
View
2  django/forms/forms.py
@@ -523,7 +523,7 @@ def label_tag(self, contents=None, attrs=None):
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
)
View
2  django/forms/formsets.py
@@ -119,7 +119,7 @@ def initial_form_count(self):
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):
View
2  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):
View
2  django/http/multipartparser.py
@@ -292,7 +292,7 @@ def tell(self):
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)
View
2  django/template/base.py
@@ -641,7 +641,7 @@ def args_check(name, func, provided):
(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)
View
4 django/template/defaulttags.py
@@ -127,7 +127,7 @@ def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empt
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)
View
2  django/utils/dateformat.py
@@ -234,7 +234,7 @@ def t(self):
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)
View
5 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):
View
2  django/utils/log.py
@@ -111,7 +111,7 @@ def emit(self, record):
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())
View
5 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
View
2  django/utils/tree.py
@@ -20,7 +20,7 @@ def __init__(self, children=None, connector=None, negated=False):
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

0 comments on commit 9c487b5

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