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

This commit is contained in:
Ramiro Morales 2013-05-26 23:47:50 -03:00
parent d228c1192e
commit 0fa8d43e74
25 changed files with 37 additions and 39 deletions

View File

@ -216,7 +216,7 @@ class RelatedFieldListFilter(FieldListFilter):
} }
FieldListFilter.register(lambda f: ( 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) isinstance(f, models.related.RelatedObject)), RelatedFieldListFilter)

View File

@ -131,7 +131,7 @@ class AdminField(object):
classes.append('required') classes.append('required')
if not self.is_first: if not self.is_first:
classes.append('inline') 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) return self.field.label_tag(contents=mark_safe(contents), attrs=attrs)
def errors(self): def errors(self):
@ -144,7 +144,7 @@ class AdminReadonlyField(object):
# {{ field.name }} must be a useful class name to identify the field. # {{ field.name }} must be a useful class name to identify the field.
# For convenience, store other field-related data here too. # For convenience, store other field-related data here too.
if callable(field): if callable(field):
class_name = field.__name__ != '<lambda>' and field.__name__ or '' class_name = field.__name__ if field.__name__ != '<lambda>' else ''
else: else:
class_name = field class_name = field
self.field = { self.field = {

View File

@ -53,4 +53,4 @@ def get_admin_log(parser, token):
if tokens[4] != 'for_user': if tokens[4] != 'for_user':
raise template.TemplateSyntaxError( raise template.TemplateSyntaxError(
"Fourth argument to 'get_admin_log' must be 'for_user'") "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 File

@ -39,7 +39,7 @@ def bookmarklets(request):
admin_root = urlresolvers.reverse('admin:index') admin_root = urlresolvers.reverse('admin:index')
return render_to_response('admin_doc/bookmarklets.html', { return render_to_response('admin_doc/bookmarklets.html', {
'root_path': admin_root, '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)) }, context_instance=RequestContext(request))
@staff_member_required @staff_member_required
@ -287,7 +287,7 @@ def template_detail(request, template):
templates.append({ templates.append({
'file': template_file, 'file': template_file,
'exists': os.path.exists(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_id': settings_mod.SITE_ID,
'site': site_obj, 'site': site_obj,
'order': list(settings_mod.TEMPLATE_DIRS).index(dir), 'order': list(settings_mod.TEMPLATE_DIRS).index(dir),

View File

@ -237,7 +237,7 @@ class PasswordResetForm(forms.Form):
'uid': int_to_base36(user.pk), 'uid': int_to_base36(user.pk),
'user': user, 'user': user,
'token': token_generator.make_token(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) subject = loader.render_to_string(subject_template_name, c)
# Email subject *must not* contain newlines # Email subject *must not* contain newlines

View File

@ -384,7 +384,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
@property @property
def wkt(self): def wkt(self):
"Returns the WKT (Well-Known Text) representation of this Geometry." "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 @property
def hex(self): def hex(self):
@ -395,7 +395,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
""" """
# A possible faster, all-python, implementation: # A possible faster, all-python, implementation:
# str(self.wkb).encode('hex') # 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 @property
def hexewkb(self): def hexewkb(self):
@ -407,7 +407,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
if self.hasz and not GEOS_PREPARE: if self.hasz and not GEOS_PREPARE:
# See: http://trac.osgeo.org/geos/ticket/216 # See: http://trac.osgeo.org/geos/ticket/216
raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D HEXEWKB.') 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 @property
def json(self): def json(self):
@ -427,7 +427,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
as a Python buffer. SRID and Z values are not included, use the as a Python buffer. SRID and Z values are not included, use the
`ewkb` property instead. `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 @property
def ewkb(self): def ewkb(self):
@ -439,7 +439,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
if self.hasz and not GEOS_PREPARE: if self.hasz and not GEOS_PREPARE:
# See: http://trac.osgeo.org/geos/ticket/216 # See: http://trac.osgeo.org/geos/ticket/216
raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D EWKB.') 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 @property
def kml(self): def kml(self):

View File

@ -546,7 +546,7 @@ class LayerMapping(object):
# Attempting to save. # Attempting to save.
m.save(using=self.using) m.save(using=self.using)
num_saved += 1 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: except SystemExit:
raise raise
except Exception as msg: except Exception as msg:

View File

@ -94,7 +94,7 @@ class Sitemap(object):
'location': loc, 'location': loc,
'lastmod': self.__get('lastmod', item, None), 'lastmod': self.__get('lastmod', item, None),
'changefreq': self.__get('changefreq', 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) urls.append(url_info)
return urls return urls

View File

@ -245,7 +245,7 @@ def find(path, all=False):
if matches: if matches:
return matches return matches
# No match. # No match.
return all and [] or None return [] if all else None
def get_finders(): def get_finders():

View File

@ -175,11 +175,9 @@ Type 'yes' to continue, or 'no' to cancel: """
summary = template % { summary = template % {
'modified_count': modified_count, 'modified_count': modified_count,
'identifier': 'static file' + ('' if modified_count == 1 else 's'), 'identifier': 'static file' + ('' if modified_count == 1 else 's'),
'action': self.symlink and 'symlinked' or 'copied', 'action': 'symlinked' if self.symlink else 'copied',
'destination': (destination_path and " to '%s'" 'destination': (" to '%s'" % destination_path if destination_path else ''),
% destination_path or ''), 'unmodified': (', %s unmodified' % unmodified_count if collected['unmodified'] else ''),
'unmodified': (collected['unmodified'] and ', %s unmodified'
% unmodified_count or ''),
'post_processed': (collected['post_processed'] and 'post_processed': (collected['post_processed'] and
', %s post-processed' ', %s post-processed'
% post_processed_count or ''), % post_processed_count or ''),

View File

@ -41,7 +41,7 @@ except (ImportError, AttributeError):
def fd(f): def fd(f):
"""Get a filedescriptor from something which could be a file or an fd.""" """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': if system_type == 'nt':
def lock(file, flags): def lock(file, flags):

View File

@ -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: with open(old_file_name, 'rb') as old_file:
# now open the new file, not forgetting allow_overwrite # 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) | 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: try:
locks.lock(fd, locks.LOCK_EX) locks.lock(fd, locks.LOCK_EX)
current_chunk = None current_chunk = None

View File

@ -38,7 +38,7 @@ class Command(LabelCommand):
qn = connection.ops.quote_name qn = connection.ops.quote_name
for f in fields: for f in fields:
field_output = [qn(f.name), f.db_type(connection=connection)] 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: if f.primary_key:
field_output.append("PRIMARY KEY") field_output.append("PRIMARY KEY")
elif f.unique: elif f.unique:
@ -51,7 +51,7 @@ class Command(LabelCommand):
table_output.append(" ".join(field_output)) table_output.append(" ".join(field_output))
full_statement = ["CREATE TABLE %s (" % qn(tablename)] full_statement = ["CREATE TABLE %s (" % qn(tablename)]
for i, line in enumerate(table_output): 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(');') full_statement.append(');')
with transaction.commit_on_success_unless_managed(): with transaction.commit_on_success_unless_managed():
curs = connection.cursor() curs = connection.cursor()

View File

@ -99,7 +99,7 @@ class Command(BaseCommand):
"started_at": datetime.now().strftime('%B %d, %Y - %X'), "started_at": datetime.now().strftime('%B %d, %Y - %X'),
"version": self.get_version(), "version": self.get_version(),
"settings": settings.SETTINGS_MODULE, "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, "port": self.port,
"quit_command": quit_command, "quit_command": quit_command,
}) })

View File

@ -97,7 +97,7 @@ class BaseDatabaseCreation(object):
style.SQL_TABLE(qn(opts.db_table)) + ' ('] style.SQL_TABLE(qn(opts.db_table)) + ' (']
for i, line in enumerate(table_output): # Combine and add commas. for i, line in enumerate(table_output): # Combine and add commas.
full_statement.append( 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(')') full_statement.append(')')
if opts.db_tablespace: if opts.db_tablespace:
tablespace_sql = self.connection.ops.tablespace_sql( tablespace_sql = self.connection.ops.tablespace_sql(

View File

@ -83,7 +83,7 @@ class CursorDebugWrapper(CursorWrapper):
############################################### ###############################################
def typecast_date(s): 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 def typecast_time(s): # does NOT store time zone information
if not s: return None if not s: return None

View File

@ -125,7 +125,7 @@ class QuerySet(object):
else: else:
stop = None stop = None
qs.query.set_limits(start, stop) 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 = self._clone()
qs.query.set_limits(k, k + 1) qs.query.set_limits(k, k + 1)

View File

@ -99,7 +99,7 @@ class Count(Aggregate):
sql_template = '%(function)s(%(distinct)s%(field)s)' sql_template = '%(function)s(%(distinct)s%(field)s)'
def __init__(self, col, distinct=False, **extra): 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): class Max(Aggregate):
sql_function = 'MAX' sql_function = 'MAX'

View File

@ -134,7 +134,7 @@ class BaseForm(object):
Subclasses may wish to override. 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): def add_initial_prefix(self, field_name):
""" """

View File

@ -85,7 +85,7 @@ class CommonMiddleware(object):
return return
if new_url[0]: if new_url[0]:
newurl = "%s://%s%s" % ( 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])) new_url[0], urlquote(new_url[1]))
else: else:
newurl = urlquote(new_url[1]) newurl = urlquote(new_url[1])

View File

@ -49,7 +49,7 @@ class LocaleMiddleware(object):
if path_valid: if path_valid:
language_url = "%s://%s/%s%s" % ( 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()) request.get_host(), language, request.get_full_path())
return HttpResponseRedirect(language_url) return HttpResponseRedirect(language_url)

View File

@ -92,8 +92,8 @@ class AdminEmailHandler(logging.Handler):
request = record.request request = record.request
subject = '%s (%s IP): %s' % ( subject = '%s (%s IP): %s' % (
record.levelname, record.levelname,
(request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
and 'internal' or 'EXTERNAL'), else 'EXTERNAL'),
record.getMessage() record.getMessage()
) )
filter = get_exception_reporter_filter(request) filter = get_exception_reporter_filter(request)

View File

@ -405,7 +405,7 @@ class ExceptionReporter(object):
if pre_context_lineno is not None: if pre_context_lineno is not None:
frames.append({ frames.append({
'tb': tb, 'tb': tb,
'type': module_name.startswith('django.') and 'django' or 'user', 'type': 'django' if module_name.startswith('django.') else 'user',
'filename': filename, 'filename': filename,
'function': function, 'function': function,
'lineno': lineno + 1, 'lineno': lineno + 1,

View File

@ -137,7 +137,7 @@ class DjangoHTMLTranslator(SmartyPantsHTMLTranslator):
) )
title = "%s%s" % ( title = "%s%s" % (
self.version_text[node['type']] % node['version'], self.version_text[node['type']] % node['version'],
len(node) and ":" or "." ":" if len(node) else "."
) )
self.body.append('<span class="title">%s</span> ' % title) self.body.append('<span class="title">%s</span> ' % title)

View File

@ -1398,7 +1398,7 @@ class FormsTestCase(TestCase):
birthday = DateField() birthday = DateField()
def add_prefix(self, field_name): 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') 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> 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>