mirror of
				https://github.com/django/django.git
				synced 2025-10-31 09:41:08 +00:00 
			
		
		
		
	Replaced and...or... constructs with PEP 308 conditional expressions.
				
					
				
			This commit is contained in:
		| @@ -216,7 +216,7 @@ class RelatedFieldListFilter(FieldListFilter): | ||||
|             } | ||||
|  | ||||
| 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) | ||||
|  | ||||
|  | ||||
|   | ||||
| @@ -131,7 +131,7 @@ class AdminField(object): | ||||
|             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 @@ class AdminReadonlyField(object): | ||||
|         # {{ 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 = { | ||||
|   | ||||
| @@ -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)) | ||||
|   | ||||
| @@ -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), | ||||
|   | ||||
| @@ -237,7 +237,7 @@ class PasswordResetForm(forms.Form): | ||||
|                 '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 | ||||
|   | ||||
| @@ -384,7 +384,7 @@ class GEOSGeometry(GEOSBase, ListMixin): | ||||
|     @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 @@ class GEOSGeometry(GEOSBase, ListMixin): | ||||
|         """ | ||||
|         # 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 @@ class GEOSGeometry(GEOSBase, ListMixin): | ||||
|         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 @@ class GEOSGeometry(GEOSBase, ListMixin): | ||||
|         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 @@ class GEOSGeometry(GEOSBase, ListMixin): | ||||
|         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): | ||||
|   | ||||
| @@ -546,7 +546,7 @@ class LayerMapping(object): | ||||
|                         # 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: | ||||
|   | ||||
| @@ -94,7 +94,7 @@ class Sitemap(object): | ||||
|                 '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 | ||||
|   | ||||
| @@ -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(): | ||||
|   | ||||
| @@ -175,11 +175,9 @@ Type 'yes' to continue, or 'no' to cancel: """ | ||||
|             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 ''), | ||||
|   | ||||
| @@ -41,7 +41,7 @@ except (ImportError, AttributeError): | ||||
|  | ||||
| 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): | ||||
|   | ||||
| @@ -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 | ||||
|   | ||||
| @@ -38,7 +38,7 @@ class Command(LabelCommand): | ||||
|         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 @@ class Command(LabelCommand): | ||||
|             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() | ||||
|   | ||||
| @@ -99,7 +99,7 @@ class Command(BaseCommand): | ||||
|             "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, | ||||
|         }) | ||||
|   | ||||
| @@ -97,7 +97,7 @@ class BaseDatabaseCreation(object): | ||||
|                           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( | ||||
|   | ||||
| @@ -83,7 +83,7 @@ class CursorDebugWrapper(CursorWrapper): | ||||
| ############################################### | ||||
|  | ||||
| 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 | ||||
|   | ||||
| @@ -125,7 +125,7 @@ class QuerySet(object): | ||||
|             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) | ||||
|   | ||||
| @@ -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' | ||||
|   | ||||
| @@ -134,7 +134,7 @@ class BaseForm(object): | ||||
|  | ||||
|         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): | ||||
|         """ | ||||
|   | ||||
| @@ -85,7 +85,7 @@ class CommonMiddleware(object): | ||||
|             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]) | ||||
|   | ||||
| @@ -49,7 +49,7 @@ class LocaleMiddleware(object): | ||||
|  | ||||
|             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) | ||||
|  | ||||
|   | ||||
| @@ -92,8 +92,8 @@ class AdminEmailHandler(logging.Handler): | ||||
|             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) | ||||
|   | ||||
| @@ -405,7 +405,7 @@ class ExceptionReporter(object): | ||||
|             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, | ||||
|   | ||||
| @@ -137,7 +137,7 @@ class DjangoHTMLTranslator(SmartyPantsHTMLTranslator): | ||||
|         ) | ||||
|         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) | ||||
|  | ||||
|   | ||||
| @@ -1398,7 +1398,7 @@ class FormsTestCase(TestCase): | ||||
|             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> | ||||
|   | ||||
		Reference in New Issue
	
	Block a user