Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Replaced `and...or...` constructs with PEP 308 conditional expressions.

  • Loading branch information...
commit 0fa8d43e742ee8b480d938a47836b5a3720c2677 1 parent d228c11
@ramiro ramiro authored
Showing with 37 additions and 39 deletions.
  1. +1 −1  django/contrib/admin/filters.py
  2. +2 −2 django/contrib/admin/helpers.py
  3. +1 −1  django/contrib/admin/templatetags/log.py
  4. +2 −2 django/contrib/admindocs/views.py
  5. +1 −1  django/contrib/auth/forms.py
  6. +5 −5 django/contrib/gis/geos/geometry.py
  7. +1 −1  django/contrib/gis/utils/layermapping.py
  8. +1 −1  django/contrib/sitemaps/__init__.py
  9. +1 −1  django/contrib/staticfiles/finders.py
  10. +3 −5 django/contrib/staticfiles/management/commands/collectstatic.py
  11. +1 −1  django/core/files/locks.py
  12. +3 −3 django/core/files/move.py
  13. +2 −2 django/core/management/commands/createcachetable.py
  14. +1 −1  django/core/management/commands/runserver.py
  15. +1 −1  django/db/backends/creation.py
  16. +1 −1  django/db/backends/util.py
  17. +1 −1  django/db/models/query.py
  18. +1 −1  django/db/models/sql/aggregates.py
  19. +1 −1  django/forms/forms.py
  20. +1 −1  django/middleware/common.py
  21. +1 −1  django/middleware/locale.py
  22. +2 −2 django/utils/log.py
  23. +1 −1  django/views/debug.py
  24. +1 −1  docs/_ext/djangodocs.py
  25. +1 −1  tests/forms_tests/tests/test_forms.py
View
2  django/contrib/admin/filters.py
@@ -216,7 +216,7 @@ def choices(self, cl):
}
FieldListFilter.register(lambda f: (
- hasattr(f, 'rel') and bool(f.rel) or
+ bool(f.rel) if hasattr(f, 'rel') else
isinstance(f, models.related.RelatedObject)), RelatedFieldListFilter)
View
4 django/contrib/admin/helpers.py
@@ -131,7 +131,7 @@ def label_tag(self):
classes.append('required')
if not self.is_first:
classes.append('inline')
- attrs = classes and {'class': ' '.join(classes)} or {}
+ attrs = {'class': ' '.join(classes)} if classes else {}
return self.field.label_tag(contents=mark_safe(contents), attrs=attrs)
def errors(self):
@@ -144,7 +144,7 @@ def __init__(self, form, field, is_first, model_admin=None):
# {{ field.name }} must be a useful class name to identify the field.
# For convenience, store other field-related data here too.
if callable(field):
- class_name = field.__name__ != '<lambda>' and field.__name__ or ''
+ class_name = field.__name__ if field.__name__ != '<lambda>' else ''
else:
class_name = field
self.field = {
View
2  django/contrib/admin/templatetags/log.py
@@ -53,4 +53,4 @@ def get_admin_log(parser, token):
if tokens[4] != 'for_user':
raise template.TemplateSyntaxError(
"Fourth argument to 'get_admin_log' must be 'for_user'")
- return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None))
+ return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(tokens[5] if len(tokens) > 5 else None))
View
4 django/contrib/admindocs/views.py
@@ -39,7 +39,7 @@ def bookmarklets(request):
admin_root = urlresolvers.reverse('admin:index')
return render_to_response('admin_doc/bookmarklets.html', {
'root_path': admin_root,
- 'admin_url': "%s://%s%s" % (request.is_secure() and 'https' or 'http', request.get_host(), admin_root),
+ 'admin_url': "%s://%s%s" % ('https' if request.is_secure() else 'http', request.get_host(), admin_root),
}, context_instance=RequestContext(request))
@staff_member_required
@@ -287,7 +287,7 @@ def template_detail(request, template):
templates.append({
'file': template_file,
'exists': os.path.exists(template_file),
- 'contents': lambda: os.path.exists(template_file) and open(template_file).read() or '',
+ 'contents': lambda: open(template_file).read() if os.path.exists(template_file) else '',
'site_id': settings_mod.SITE_ID,
'site': site_obj,
'order': list(settings_mod.TEMPLATE_DIRS).index(dir),
View
2  django/contrib/auth/forms.py
@@ -237,7 +237,7 @@ def save(self, domain_override=None,
'uid': int_to_base36(user.pk),
'user': user,
'token': token_generator.make_token(user),
- 'protocol': use_https and 'https' or 'http',
+ 'protocol': 'https' if use_https else 'http',
}
subject = loader.render_to_string(subject_template_name, c)
# Email subject *must not* contain newlines
View
10 django/contrib/gis/geos/geometry.py
@@ -384,7 +384,7 @@ def ewkt(self):
@property
def wkt(self):
"Returns the WKT (Well-Known Text) representation of this Geometry."
- return wkt_w(self.hasz and 3 or 2).write(self).decode()
+ return wkt_w(3 if self.hasz else 2).write(self).decode()
@property
def hex(self):
@@ -395,7 +395,7 @@ def hex(self):
"""
# A possible faster, all-python, implementation:
# str(self.wkb).encode('hex')
- return wkb_w(self.hasz and 3 or 2).write_hex(self)
+ return wkb_w(3 if self.hasz else 2).write_hex(self)
@property
def hexewkb(self):
@@ -407,7 +407,7 @@ def hexewkb(self):
if self.hasz and not GEOS_PREPARE:
# See: http://trac.osgeo.org/geos/ticket/216
raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D HEXEWKB.')
- return ewkb_w(self.hasz and 3 or 2).write_hex(self)
+ return ewkb_w(3 if self.hasz else 2).write_hex(self)
@property
def json(self):
@@ -427,7 +427,7 @@ def wkb(self):
as a Python buffer. SRID and Z values are not included, use the
`ewkb` property instead.
"""
- return wkb_w(self.hasz and 3 or 2).write(self)
+ return wkb_w(3 if self.hasz else 2).write(self)
@property
def ewkb(self):
@@ -439,7 +439,7 @@ def ewkb(self):
if self.hasz and not GEOS_PREPARE:
# See: http://trac.osgeo.org/geos/ticket/216
raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D EWKB.')
- return ewkb_w(self.hasz and 3 or 2).write(self)
+ return ewkb_w(3 if self.hasz else 2).write(self)
@property
def kml(self):
View
2  django/contrib/gis/utils/layermapping.py
@@ -546,7 +546,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
# Attempting to save.
m.save(using=self.using)
num_saved += 1
- if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m))
+ if verbose: stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m))
except SystemExit:
raise
except Exception as msg:
View
2  django/contrib/sitemaps/__init__.py
@@ -94,7 +94,7 @@ def get_urls(self, page=1, site=None, protocol=None):
'location': loc,
'lastmod': self.__get('lastmod', item, None),
'changefreq': self.__get('changefreq', item, None),
- 'priority': str(priority is not None and priority or ''),
+ 'priority': str(priority if priority is not None else ''),
}
urls.append(url_info)
return urls
View
2  django/contrib/staticfiles/finders.py
@@ -245,7 +245,7 @@ def find(path, all=False):
if matches:
return matches
# No match.
- return all and [] or None
+ return [] if all else None
def get_finders():
View
8 django/contrib/staticfiles/management/commands/collectstatic.py
@@ -175,11 +175,9 @@ def handle_noargs(self, **options):
summary = template % {
'modified_count': modified_count,
'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 ''),
- 'unmodified': (collected['unmodified'] and ', %s unmodified'
- % unmodified_count or ''),
+ 'action': 'symlinked' if self.symlink else 'copied',
+ 'destination': (" to '%s'" % destination_path if destination_path else ''),
+ 'unmodified': (', %s unmodified' % unmodified_count if collected['unmodified'] else ''),
'post_processed': (collected['post_processed'] and
', %s post-processed'
% post_processed_count or ''),
View
2  django/core/files/locks.py
@@ -41,7 +41,7 @@
def fd(f):
"""Get a filedescriptor from something which could be a file or an fd."""
- return hasattr(f, 'fileno') and f.fileno() or f
+ return f.fileno() if hasattr(f, 'fileno') else f
if system_type == 'nt':
def lock(file, flags):
View
6 django/core/files/move.py
@@ -62,7 +62,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove
with open(old_file_name, 'rb') as old_file:
# now open the new file, not forgetting allow_overwrite
fd = os.open(new_file_name, os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) |
- (not allow_overwrite and os.O_EXCL or 0))
+ (os.O_EXCL if not allow_overwrite else 0))
try:
locks.lock(fd, locks.LOCK_EX)
current_chunk = None
@@ -77,8 +77,8 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove
try:
os.remove(old_file_name)
except OSError as e:
- # Certain operating systems (Cygwin and Windows)
- # fail when deleting opened files, ignore it. (For the
+ # Certain operating systems (Cygwin and Windows)
+ # fail when deleting opened files, ignore it. (For the
# systems where this happens, temporary files will be auto-deleted
# on close anyway.)
if getattr(e, 'winerror', 0) != 32 and getattr(e, 'errno', 0) != 13:
View
4 django/core/management/commands/createcachetable.py
@@ -38,7 +38,7 @@ def handle_label(self, tablename, **options):
qn = connection.ops.quote_name
for f in fields:
field_output = [qn(f.name), f.db_type(connection=connection)]
- field_output.append("%sNULL" % (not f.null and "NOT " or ""))
+ field_output.append("%sNULL" % ("NOT " if not f.null else ""))
if f.primary_key:
field_output.append("PRIMARY KEY")
elif f.unique:
@@ -51,7 +51,7 @@ def handle_label(self, tablename, **options):
table_output.append(" ".join(field_output))
full_statement = ["CREATE TABLE %s (" % qn(tablename)]
for i, line in enumerate(table_output):
- full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or ''))
+ full_statement.append(' %s%s' % (line, ',' if i < len(table_output)-1 else ''))
full_statement.append(');')
with transaction.commit_on_success_unless_managed():
curs = connection.cursor()
View
2  django/core/management/commands/runserver.py
@@ -99,7 +99,7 @@ def inner_run(self, *args, **options):
"started_at": datetime.now().strftime('%B %d, %Y - %X'),
"version": self.get_version(),
"settings": settings.SETTINGS_MODULE,
- "addr": self._raw_ipv6 and '[%s]' % self.addr or self.addr,
+ "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr,
"port": self.port,
"quit_command": quit_command,
})
View
2  django/db/backends/creation.py
@@ -97,7 +97,7 @@ def sql_create_model(self, model, style, known_models=set()):
style.SQL_TABLE(qn(opts.db_table)) + ' (']
for i, line in enumerate(table_output): # Combine and add commas.
full_statement.append(
- ' %s%s' % (line, i < len(table_output) - 1 and ',' or ''))
+ ' %s%s' % (line, ',' if i < len(table_output) - 1 else ''))
full_statement.append(')')
if opts.db_tablespace:
tablespace_sql = self.connection.ops.tablespace_sql(
View
2  django/db/backends/util.py
@@ -83,7 +83,7 @@ def executemany(self, sql, param_list):
###############################################
def typecast_date(s):
- return s and datetime.date(*map(int, s.split('-'))) or None # returns None if s is null
+ return datetime.date(*map(int, s.split('-'))) if s else None # returns None if s is null
def typecast_time(s): # does NOT store time zone information
if not s: return None
View
2  django/db/models/query.py
@@ -125,7 +125,7 @@ def __getitem__(self, k):
else:
stop = None
qs.query.set_limits(start, stop)
- return k.step and list(qs)[::k.step] or qs
+ return list(qs)[::k.step] if k.step else qs
qs = self._clone()
qs.query.set_limits(k, k + 1)
View
2  django/db/models/sql/aggregates.py
@@ -99,7 +99,7 @@ class Count(Aggregate):
sql_template = '%(function)s(%(distinct)s%(field)s)'
def __init__(self, col, distinct=False, **extra):
- super(Count, self).__init__(col, distinct=distinct and 'DISTINCT ' or '', **extra)
+ super(Count, self).__init__(col, distinct='DISTINCT ' if distinct else '', **extra)
class Max(Aggregate):
sql_function = 'MAX'
View
2  django/forms/forms.py
@@ -134,7 +134,7 @@ def add_prefix(self, field_name):
Subclasses may wish to override.
"""
- return self.prefix and ('%s-%s' % (self.prefix, field_name)) or field_name
+ return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name
def add_initial_prefix(self, field_name):
"""
View
2  django/middleware/common.py
@@ -85,7 +85,7 @@ def process_request(self, request):
return
if new_url[0]:
newurl = "%s://%s%s" % (
- request.is_secure() and 'https' or 'http',
+ 'https' if request.is_secure() else 'http',
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
View
2  django/middleware/locale.py
@@ -49,7 +49,7 @@ def process_response(self, request, response):
if path_valid:
language_url = "%s://%s/%s%s" % (
- request.is_secure() and 'https' or 'http',
+ 'https' if request.is_secure() else 'http',
request.get_host(), language, request.get_full_path())
return HttpResponseRedirect(language_url)
View
4 django/utils/log.py
@@ -92,8 +92,8 @@ def emit(self, record):
request = record.request
subject = '%s (%s IP): %s' % (
record.levelname,
- (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
- and 'internal' or 'EXTERNAL'),
+ ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
+ else 'EXTERNAL'),
record.getMessage()
)
filter = get_exception_reporter_filter(request)
View
2  django/views/debug.py
@@ -405,7 +405,7 @@ def get_traceback_frames(self):
if pre_context_lineno is not None:
frames.append({
'tb': tb,
- 'type': module_name.startswith('django.') and 'django' or 'user',
+ 'type': 'django' if module_name.startswith('django.') else 'user',
'filename': filename,
'function': function,
'lineno': lineno + 1,
View
2  docs/_ext/djangodocs.py
@@ -137,7 +137,7 @@ def visit_versionmodified(self, node):
)
title = "%s%s" % (
self.version_text[node['type']] % node['version'],
- len(node) and ":" or "."
+ ":" if len(node) else "."
)
self.body.append('<span class="title">%s</span> ' % title)
View
2  tests/forms_tests/tests/test_forms.py
@@ -1398,7 +1398,7 @@ class Person(Form):
birthday = DateField()
def add_prefix(self, field_name):
- return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
+ return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name
p = Person(prefix='foo')
self.assertHTMLEqual(p.as_ul(), """<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li>
Please sign in to comment.
Something went wrong with that request. Please try again.