diff --git a/django/contrib/admin/filters.py b/django/contrib/admin/filters.py
index 3a37de2404..2a9fb2a8f9 100644
--- a/django/contrib/admin/filters.py
+++ b/django/contrib/admin/filters.py
@@ -287,8 +287,8 @@ FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter)
class DateFieldListFilter(FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.field_generic = '%s__' % field_path
- self.date_params = dict([(k, v) for k, v in params.items()
- if k.startswith(self.field_generic)])
+ self.date_params = dict((k, v) for k, v in params.items()
+ if k.startswith(self.field_generic))
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
index b6d5bde932..af1df5e668 100644
--- a/django/contrib/admin/helpers.py
+++ b/django/contrib/admin/helpers.py
@@ -112,7 +112,7 @@ class Fieldline(object):
yield AdminField(self.form, field, is_first=(i == 0))
def errors(self):
- return mark_safe('\n'.join([self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields]).strip('\n'))
+ return mark_safe('\n'.join(self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields).strip('\n'))
class AdminField(object):
def __init__(self, form, field, is_first):
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index 805868306d..d435675eae 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -698,16 +698,16 @@ class ModelAdmin(BaseModelAdmin):
# Avoid trying to iterate over None
if not class_actions:
continue
- actions.extend([self.get_action(action) for action in class_actions])
+ actions.extend(self.get_action(action) for action in class_actions)
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
# Convert the actions into an OrderedDict keyed by name.
- actions = OrderedDict([
+ actions = OrderedDict(
(name, (func, name, desc))
for func, name, desc in actions
- ])
+ )
return actions
diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
index 5773db6394..e5b590e0d0 100644
--- a/django/contrib/admin/widgets.py
+++ b/django/contrib/admin/widgets.py
@@ -119,7 +119,7 @@ def url_params_from_lookup_dict(lookups):
if callable(v):
v = v()
if isinstance(v, (tuple, list)):
- v = ','.join([str(x) for x in v])
+ v = ','.join(str(x) for x in v)
elif isinstance(v, bool):
# See django.db.fields.BooleanField.get_prep_lookup
v = ('0', '1')[v]
@@ -154,7 +154,7 @@ class ForeignKeyRawIdWidget(forms.TextInput):
params = self.url_parameters()
if params:
- url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in params.items()])
+ url = '?' + '&'.join('%s=%s' % (k, v) for k, v in params.items())
else:
url = ''
if "class" not in attrs:
@@ -199,7 +199,7 @@ class ManyToManyRawIdWidget(ForeignKeyRawIdWidget):
# The related object is registered with the same AdminSite
attrs['class'] = 'vManyToManyRawIdAdminField'
if value:
- value = ','.join([force_text(v) for v in value])
+ value = ','.join(force_text(v) for v in value)
else:
value = ''
return super(ManyToManyRawIdWidget, self).render(name, value, attrs)
diff --git a/django/contrib/admindocs/utils.py b/django/contrib/admindocs/utils.py
index 9be0093dfc..c97d588c7d 100644
--- a/django/contrib/admindocs/utils.py
+++ b/django/contrib/admindocs/utils.py
@@ -26,7 +26,7 @@ def trim_docstring(docstring):
return ''
# Convert tabs to spaces and split into lines
lines = docstring.expandtabs().splitlines()
- indent = min([len(line) - len(line.lstrip()) for line in lines if line.lstrip()])
+ indent = min(len(line) - len(line.lstrip()) for line in lines if line.lstrip())
trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]]
return "\n".join(trimmed).strip()
diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py
index cb79291c17..7304ccd14e 100644
--- a/django/contrib/auth/backends.py
+++ b/django/contrib/auth/backends.py
@@ -36,14 +36,14 @@ class ModelBackend(object):
user_groups_query = 'group__%s' % user_groups_field.related_query_name()
perms = Permission.objects.filter(**{user_groups_query: user_obj})
perms = perms.values_list('content_type__app_label', 'codename').order_by()
- user_obj._group_perm_cache = set(["%s.%s" % (ct, name) for ct, name in perms])
+ user_obj._group_perm_cache = set("%s.%s" % (ct, name) for ct, name in perms)
return user_obj._group_perm_cache
def get_all_permissions(self, user_obj, obj=None):
if user_obj.is_anonymous() or obj is not None:
return set()
if not hasattr(user_obj, '_perm_cache'):
- user_obj._perm_cache = set(["%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related()])
+ user_obj._perm_cache = set("%s.%s" % (p.content_type.app_label, p.codename) for p in user_obj.user_permissions.select_related())
user_obj._perm_cache.update(self.get_group_permissions(user_obj))
return user_obj._perm_cache
diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
index 3eba8abd51..474badeb92 100644
--- a/django/contrib/auth/forms.py
+++ b/django/contrib/auth/forms.py
@@ -330,10 +330,10 @@ class PasswordChangeForm(SetPasswordForm):
)
return old_password
-PasswordChangeForm.base_fields = OrderedDict([
+PasswordChangeForm.base_fields = OrderedDict(
(k, PasswordChangeForm.base_fields[k])
for k in ['old_password', 'new_password1', 'new_password2']
-])
+)
class AdminPasswordChangeForm(forms.Form):
diff --git a/django/contrib/contenttypes/management.py b/django/contrib/contenttypes/management.py
index 4278bbd1e7..3d2fc4b95e 100644
--- a/django/contrib/contenttypes/management.py
+++ b/django/contrib/contenttypes/management.py
@@ -58,10 +58,10 @@ def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, *
# Confirm that the content type is stale before deletion.
if to_remove:
if kwargs.get('interactive', False):
- content_type_display = '\n'.join([
+ content_type_display = '\n'.join(
' %s | %s' % (ct.app_label, ct.model)
for ct in to_remove
- ])
+ )
ok_to_delete = input("""The following content types are stale and need to be deleted:
%s
diff --git a/django/contrib/gis/db/models/sql/aggregates.py b/django/contrib/gis/db/models/sql/aggregates.py
index ae848c0894..a3a8f1258d 100644
--- a/django/contrib/gis/db/models/sql/aggregates.py
+++ b/django/contrib/gis/db/models/sql/aggregates.py
@@ -32,7 +32,7 @@ class GeoAggregate(Aggregate):
if hasattr(self.col, 'as_sql'):
field_name, params = self.col.as_sql(qn, connection)
elif isinstance(self.col, (list, tuple)):
- field_name = '.'.join([qn(c) for c in self.col])
+ field_name = '.'.join(qn(c) for c in self.col)
else:
field_name = self.col
diff --git a/django/contrib/gis/feeds.py b/django/contrib/gis/feeds.py
index d7c52bf019..89bc8c531e 100644
--- a/django/contrib/gis/feeds.py
+++ b/django/contrib/gis/feeds.py
@@ -15,7 +15,7 @@ class GeoFeedMixin(object):
a single white space. Given a tuple of coordinates, this will return
a unicode GeoRSS representation.
"""
- return ' '.join(['%f %f' % (coord[1], coord[0]) for coord in coords])
+ return ' '.join('%f %f' % (coord[1], coord[0]) for coord in coords)
def add_georss_point(self, handler, coords, w3c_geo=False):
"""
diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py
index c5a87f40e0..6f8c830e1d 100644
--- a/django/contrib/gis/gdal/geometries.py
+++ b/django/contrib/gis/gdal/geometries.py
@@ -575,7 +575,7 @@ class LineString(OGRGeometry):
@property
def tuple(self):
"Returns the tuple representation of this LineString."
- return tuple([self[i] for i in xrange(len(self))])
+ return tuple(self[i] for i in xrange(len(self)))
coords = tuple
def _listarr(self, func):
@@ -632,14 +632,14 @@ class Polygon(OGRGeometry):
@property
def tuple(self):
"Returns a tuple of LinearRing coordinate tuples."
- return tuple([self[i].tuple for i in xrange(self.geom_count)])
+ return tuple(self[i].tuple for i in xrange(self.geom_count))
coords = tuple
@property
def point_count(self):
"The number of Points in this Polygon."
# Summing up the number of points in each ring of the Polygon.
- return sum([self[i].point_count for i in xrange(self.geom_count)])
+ return sum(self[i].point_count for i in xrange(self.geom_count))
@property
def centroid(self):
@@ -686,12 +686,12 @@ class GeometryCollection(OGRGeometry):
def point_count(self):
"The number of Points in this Geometry Collection."
# Summing up the number of points in each geometry in this collection
- return sum([self[i].point_count for i in xrange(self.geom_count)])
+ return sum(self[i].point_count for i in xrange(self.geom_count))
@property
def tuple(self):
"Returns a tuple representation of this Geometry Collection."
- return tuple([self[i].tuple for i in xrange(self.geom_count)])
+ return tuple(self[i].tuple for i in xrange(self.geom_count))
coords = tuple
# Multiple Geometry types.
diff --git a/django/contrib/gis/geos/collections.py b/django/contrib/gis/geos/collections.py
index 83153f85bd..70cb4e1391 100644
--- a/django/contrib/gis/geos/collections.py
+++ b/django/contrib/gis/geos/collections.py
@@ -82,7 +82,7 @@ class GeometryCollection(GEOSGeometry):
@property
def kml(self):
"Returns the KML for this Geometry Collection."
- return '%s' % ''.join([g.kml for g in self])
+ return '%s' % ''.join(g.kml for g in self)
@property
def tuple(self):
diff --git a/django/contrib/gis/geos/coordseq.py b/django/contrib/gis/geos/coordseq.py
index acf34f7262..b28fb0c524 100644
--- a/django/contrib/gis/geos/coordseq.py
+++ b/django/contrib/gis/geos/coordseq.py
@@ -147,11 +147,11 @@ class GEOSCoordSeq(GEOSBase):
if self.hasz: substr = '%s,%s,%s '
else: substr = '%s,%s,0 '
return '%s' % \
- ''.join([substr % self[i] for i in xrange(len(self))]).strip()
+ ''.join(substr % self[i] for i in xrange(len(self))).strip()
@property
def tuple(self):
"Returns a tuple version of this coordinate sequence."
n = self.size
if n == 1: return self[0]
- else: return tuple([self[i] for i in xrange(n)])
+ else: return tuple(self[i] for i in xrange(n))
diff --git a/django/contrib/gis/geos/polygon.py b/django/contrib/gis/geos/polygon.py
index c50f549e7a..53dfd67ae6 100644
--- a/django/contrib/gis/geos/polygon.py
+++ b/django/contrib/gis/geos/polygon.py
@@ -159,12 +159,12 @@ class Polygon(GEOSGeometry):
@property
def tuple(self):
"Gets the tuple for each ring in this Polygon."
- return tuple([self[i].tuple for i in xrange(len(self))])
+ return tuple(self[i].tuple for i in xrange(len(self)))
coords = tuple
@property
def kml(self):
"Returns the KML representation of this Polygon."
- inner_kml = ''.join(["%s" % self[i+1].kml
- for i in xrange(self.num_interior_rings)])
+ inner_kml = ''.join("%s" % self[i+1].kml
+ for i in xrange(self.num_interior_rings))
return "%s%s" % (self[0].kml, inner_kml)
diff --git a/django/contrib/gis/geos/tests/test_geos.py b/django/contrib/gis/geos/tests/test_geos.py
index 87aba723b9..f3a96cc992 100644
--- a/django/contrib/gis/geos/tests/test_geos.py
+++ b/django/contrib/gis/geos/tests/test_geos.py
@@ -838,9 +838,9 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
# Creating a GeometryCollection WKT string composed of other
# collections and polygons.
coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid]
- coll.extend([mls.wkt for mls in self.geometries.multilinestrings])
- coll.extend([p.wkt for p in self.geometries.polygons])
- coll.extend([mp.wkt for mp in self.geometries.multipoints])
+ coll.extend(mls.wkt for mls in self.geometries.multilinestrings)
+ coll.extend(p.wkt for p in self.geometries.polygons)
+ coll.extend(mp.wkt for mp in self.geometries.multipoints)
gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)
# Should construct ok from WKT
diff --git a/django/contrib/gis/management/commands/ogrinspect.py b/django/contrib/gis/management/commands/ogrinspect.py
index 85118e3a94..1270432438 100644
--- a/django/contrib/gis/management/commands/ogrinspect.py
+++ b/django/contrib/gis/management/commands/ogrinspect.py
@@ -113,6 +113,6 @@ class Command(LabelCommand):
rev_mapping = dict((v, k) for k, v in mapping_dict.items())
output.extend(['', '# Auto-generated `LayerMapping` dictionary for %s model' % model_name,
'%s_mapping = {' % model_name.lower()])
- output.extend([" '%s' : '%s'," % (rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields])
- output.extend([" '%s' : '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}'])
+ output.extend(" '%s' : '%s'," % (rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options['layer_key']].fields)
+ output.extend(" '%s' : '%s'," % (options['geom_name'], mapping_dict[options['geom_name']]), '}')
return '\n'.join(output) + '\n'
diff --git a/django/contrib/gis/maps/google/gmap.py b/django/contrib/gis/maps/google/gmap.py
index ff6562696d..95cf2c9d99 100644
--- a/django/contrib/gis/maps/google/gmap.py
+++ b/django/contrib/gis/maps/google/gmap.py
@@ -150,7 +150,7 @@ class GoogleMap(object):
@property
def icons(self):
"Returns a sequence of GIcon objects in this map."
- return set([marker.icon for marker in self.markers if marker.icon])
+ return set(marker.icon for marker in self.markers if marker.icon)
class GoogleMapSet(GoogleMap):
diff --git a/django/contrib/gis/maps/google/overlays.py b/django/contrib/gis/maps/google/overlays.py
index b82d967da6..674f02d85f 100644
--- a/django/contrib/gis/maps/google/overlays.py
+++ b/django/contrib/gis/maps/google/overlays.py
@@ -61,7 +61,7 @@ class GOverlayBase(object):
def latlng_from_coords(self, coords):
"Generates a JavaScript array of GLatLng objects for the given coordinates."
- return '[%s]' % ','.join(['new GLatLng(%s,%s)' % (y, x) for x, y in coords])
+ return '[%s]' % ','.join('new GLatLng(%s,%s)' % (y, x) for x, y in coords)
def add_event(self, event):
"Attaches a GEvent to the overlay object."
diff --git a/django/contrib/gis/tests/geoadmin/tests.py b/django/contrib/gis/tests/geoadmin/tests.py
index 295c1de46f..ebeb22338c 100644
--- a/django/contrib/gis/tests/geoadmin/tests.py
+++ b/django/contrib/gis/tests/geoadmin/tests.py
@@ -23,7 +23,7 @@ class GeoAdminTest(TestCase):
def test_ensure_geographic_media(self):
geoadmin = admin.site._registry[City]
admin_js = geoadmin.media.render_js()
- self.assertTrue(any([geoadmin.openlayers_url in js for js in admin_js]))
+ self.assertTrue(any(geoadmin.openlayers_url in js for js in admin_js))
def test_olmap_OSM_rendering(self):
geoadmin = admin.site._registry[City]
diff --git a/django/contrib/gis/tests/geoapp/test_feeds.py b/django/contrib/gis/tests/geoapp/test_feeds.py
index 9c7b572e99..fac81614c9 100644
--- a/django/contrib/gis/tests/geoapp/test_feeds.py
+++ b/django/contrib/gis/tests/geoapp/test_feeds.py
@@ -28,7 +28,7 @@ class GeoFeedTest(TestCase):
def assertChildNodes(self, elem, expected):
"Taken from syndication/tests.py."
- actual = set([n.nodeName for n in elem.childNodes])
+ actual = set(n.nodeName for n in elem.childNodes)
expected = set(expected)
self.assertEqual(actual, expected)
diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py
index bb68039bc3..92d70e1fd5 100644
--- a/django/contrib/gis/tests/geoapp/test_sitemaps.py
+++ b/django/contrib/gis/tests/geoapp/test_sitemaps.py
@@ -32,7 +32,7 @@ class GeoSitemapTest(TestCase):
def assertChildNodes(self, elem, expected):
"Taken from syndication/tests.py."
- actual = set([n.nodeName for n in elem.childNodes])
+ actual = set(n.nodeName for n in elem.childNodes)
expected = set(expected)
self.assertEqual(actual, expected)
diff --git a/django/contrib/gis/utils/wkt.py b/django/contrib/gis/utils/wkt.py
index d60eed31bd..bd85591375 100644
--- a/django/contrib/gis/utils/wkt.py
+++ b/django/contrib/gis/utils/wkt.py
@@ -30,10 +30,10 @@ def precision_wkt(geom, prec):
coord_fmt = ' '.join([num_fmt, num_fmt])
def formatted_coords(coords):
- return ','.join([coord_fmt % c[:2] for c in coords])
+ return ','.join(coord_fmt % c[:2] for c in coords)
def formatted_poly(poly):
- return ','.join(['(%s)' % formatted_coords(r) for r in poly])
+ return ','.join('(%s)' % formatted_coords(r) for r in poly)
def formatted_geom(g):
gtype = str(g.geom_type).upper()
@@ -47,11 +47,11 @@ def precision_wkt(geom, prec):
elif gtype == 'MULTIPOINT':
yield formatted_coords(g.coords)
elif gtype == 'MULTIPOLYGON':
- yield ','.join(['(%s)' % formatted_poly(p) for p in g])
+ yield ','.join('(%s)' % formatted_poly(p) for p in g)
elif gtype == 'GEOMETRYCOLLECTION':
- yield ','.join([''.join([wkt for wkt in formatted_geom(child)]) for child in g])
+ yield ','.join(''.join(wkt for wkt in formatted_geom(child)) for child in g)
else:
raise TypeError
yield ')'
- return ''.join([wkt for wkt in formatted_geom(geom)])
+ return ''.join(wkt for wkt in formatted_geom(geom))
diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py
index 8c394d2046..b6c3384358 100644
--- a/django/contrib/messages/storage/cookie.py
+++ b/django/contrib/messages/storage/cookie.py
@@ -38,8 +38,8 @@ class MessageDecoder(json.JSONDecoder):
return Message(*obj[2:])
return [self.process_messages(item) for item in obj]
if isinstance(obj, dict):
- return dict([(key, self.process_messages(value))
- for key, value in six.iteritems(obj)])
+ return dict((key, self.process_messages(value))
+ for key, value in six.iteritems(obj))
return obj
def decode(self, s, **kwargs):
diff --git a/django/contrib/webdesign/lorem_ipsum.py b/django/contrib/webdesign/lorem_ipsum.py
index 01d8f220f5..36680c81a3 100644
--- a/django/contrib/webdesign/lorem_ipsum.py
+++ b/django/contrib/webdesign/lorem_ipsum.py
@@ -62,7 +62,7 @@ def paragraph():
The paragraph consists of between 1 and 4 sentences, inclusive.
"""
- return ' '.join([sentence() for i in range(random.randint(1, 4))])
+ return ' '.join(sentence() for i in range(random.randint(1, 4)))
def paragraphs(count, common=True):
"""
diff --git a/django/core/cache/utils.py b/django/core/cache/utils.py
index b9806cc5e0..dd9ad4abd1 100644
--- a/django/core/cache/utils.py
+++ b/django/core/cache/utils.py
@@ -10,6 +10,6 @@ TEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s'
def make_template_fragment_key(fragment_name, vary_on=None):
if vary_on is None:
vary_on = ()
- key = ':'.join([urlquote(var) for var in vary_on])
+ key = ':'.join(urlquote(var) for var in vary_on)
args = hashlib.md5(force_bytes(key))
return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())
diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py
index 708cfc259a..7a7a7bb09d 100644
--- a/django/core/management/__init__.py
+++ b/django/core/management/__init__.py
@@ -114,8 +114,8 @@ def get_commands():
for app_name in apps:
try:
path = find_management_module(app_name)
- _commands.update(dict([(name, app_name)
- for name in find_commands(path)]))
+ _commands.update(dict((name, app_name)
+ for name in find_commands(path)))
except ImportError:
pass # No management module - ignore this app
@@ -336,7 +336,7 @@ class ManagementUtility(object):
options = [opt for opt in options if opt[0] not in prev_opts]
# filter options by current input
- options = sorted([(k, v) for k, v in options if k.startswith(curr)])
+ options = sorted((k, v) for k, v in options if k.startswith(curr))
for option in options:
opt_label = option[0]
# append '=' to options which require args
diff --git a/django/core/management/commands/migrate.py b/django/core/management/commands/migrate.py
index dbec389bed..9899be7e03 100644
--- a/django/core/management/commands/migrate.py
+++ b/django/core/management/commands/migrate.py
@@ -164,7 +164,7 @@ class Command(BaseCommand):
for app_name, model_list in all_models
)
- create_models = set([x for x in itertools.chain(*manifest.values())])
+ create_models = set(itertools.chain(*manifest.values()))
emit_pre_migrate_signal(create_models, self.verbosity, self.interactive, connection.alias)
# Create the tables for each model
diff --git a/django/core/management/sql.py b/django/core/management/sql.py
index 2e977c0c07..379def27dc 100644
--- a/django/core/management/sql.py
+++ b/django/core/management/sql.py
@@ -29,7 +29,7 @@ def sql_create(app, style, connection):
app_models = models.get_models(app, include_auto_created=True)
final_output = []
tables = connection.introspection.table_names()
- known_models = set([model for model in connection.introspection.installed_models(tables) if model not in app_models])
+ known_models = set(model for model in connection.introspection.installed_models(tables) if model not in app_models)
pending_references = {}
for model in app_models:
diff --git a/django/core/management/utils.py b/django/core/management/utils.py
index d1052d5182..bc007208f0 100644
--- a/django/core/management/utils.py
+++ b/django/core/management/utils.py
@@ -52,7 +52,7 @@ def handle_extensions(extensions=('html',), ignored=('py',)):
for i, ext in enumerate(ext_list):
if not ext.startswith('.'):
ext_list[i] = '.%s' % ext_list[i]
- return set([x for x in ext_list if x.strip('.') not in ignored])
+ return set(x for x in ext_list if x.strip('.') not in ignored)
def find_command(cmd, path=None, pathext=None):
if path is None:
diff --git a/django/core/management/validation.py b/django/core/management/validation.py
index 10f662152d..1c23871481 100644
--- a/django/core/management/validation.py
+++ b/django/core/management/validation.py
@@ -161,7 +161,7 @@ def get_validation_errors(outfile, app=None):
for rel_field in f.foreign_related_fields:
has_unique_field = has_unique_field or rel_field.unique
if not has_unique_field:
- e.add(opts, "Field combination '%s' under model '%s' must have a unique=True constraint" % (','.join([rel_field.name for rel_field in f.foreign_related_fields]), f.rel.to.__name__))
+ e.add(opts, "Field combination '%s' under model '%s' must have a unique=True constraint" % (','.join(rel_field.name for rel_field in f.foreign_related_fields), f.rel.to.__name__))
else:
if not f.foreign_related_fields[0].unique:
e.add(opts, "Field '%s' under model '%s' must have a unique=True constraint." % (f.foreign_related_fields[0].name, f.rel.to.__name__))
diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
index 9e086a453a..1422bf7089 100644
--- a/django/core/urlresolvers.py
+++ b/django/core/urlresolvers.py
@@ -62,7 +62,7 @@ class ResolverMatch(object):
@property
def view_name(self):
- return ':'.join([ x for x in [ self.namespace, self.url_name ] if x ])
+ return ':'.join(filter(bool, (self.namespace, self.url_name)))
def __getitem__(self, index):
return (self.func, self.args, self.kwargs)[index]
@@ -274,7 +274,7 @@ class RegexURLResolver(LocaleRegexProvider):
for matches, pat, defaults in pattern.reverse_dict.getlist(name):
new_matches = []
for piece, p_args in parent:
- new_matches.extend([(piece + suffix, p_args + args) for (suffix, args) in matches])
+ new_matches.extend((piece + suffix, p_args + args) for (suffix, args) in matches)
lookups.appendlist(name, (new_matches, p_pattern + pat, dict(defaults, **pattern.default_kwargs)))
for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items():
namespaces[namespace] = (p_pattern + prefix, sub_pattern)
@@ -321,7 +321,7 @@ class RegexURLResolver(LocaleRegexProvider):
except Resolver404 as e:
sub_tried = e.args[0].get('tried')
if sub_tried is not None:
- tried.extend([[pattern] + t for t in sub_tried])
+ tried.extend([pattern] + t for t in sub_tried)
else:
tried.append([pattern])
else:
diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py
index 6274d5bc55..0c1c329202 100644
--- a/django/db/backends/__init__.py
+++ b/django/db/backends/__init__.py
@@ -1255,7 +1255,7 @@ class BaseDatabaseIntrospection(object):
if not router.allow_migrate(self.connection.alias, model):
continue
tables.add(model._meta.db_table)
- tables.update([f.m2m_db_table() for f in model._meta.local_many_to_many])
+ tables.update(f.m2m_db_table() for f in model._meta.local_many_to_many)
tables = list(tables)
if only_existing:
existing_tables = self.table_names()
diff --git a/django/db/backends/mysql/compiler.py b/django/db/backends/mysql/compiler.py
index b7d1d7b98d..ee7fbe2575 100644
--- a/django/db/backends/mysql/compiler.py
+++ b/django/db/backends/mysql/compiler.py
@@ -20,7 +20,7 @@ class SQLCompiler(compiler.SQLCompiler):
def as_subquery_condition(self, alias, columns, qn):
qn2 = self.connection.ops.quote_name
sql, params = self.as_sql()
- return '(%s) IN (%s)' % (', '.join(['%s.%s' % (qn(alias), qn2(column)) for column in columns]), sql), params
+ return '(%s) IN (%s)' % (', '.join('%s.%s' % (qn(alias), qn2(column)) for column in columns), sql), params
class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py
index d7a29057de..6e3b8d4ea0 100644
--- a/django/db/backends/mysql/introspection.py
+++ b/django/db/backends/mysql/introspection.py
@@ -54,7 +54,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
SELECT column_name, numeric_precision, numeric_scale FROM information_schema.columns
WHERE table_name = %s AND table_schema = DATABASE()
AND data_type='decimal'""", [table_name])
- numeric_map = dict([(line[0], tuple([int(n) for n in line[1:]])) for line in cursor.fetchall()])
+ numeric_map = dict((line[0], tuple(int(n) for n in line[1:])) for line in cursor.fetchall())
cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
return [FieldInfo(*((force_text(line[0]),)
@@ -69,7 +69,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based.
"""
- return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))])
+ return dict((d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name)))
def get_relations(self, cursor, table_name):
"""
diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
index a8421991b0..a6ff26dd36 100644
--- a/django/db/backends/oracle/base.py
+++ b/django/db/backends/oracle/base.py
@@ -860,12 +860,12 @@ class FormatStylePlaceholderCursor(object):
def fetchmany(self, size=None):
if size is None:
size = self.arraysize
- return tuple([_rowfactory(r, self.cursor)
- for r in self.cursor.fetchmany(size)])
+ return tuple(_rowfactory(r, self.cursor)
+ for r in self.cursor.fetchmany(size))
def fetchall(self):
- return tuple([_rowfactory(r, self.cursor)
- for r in self.cursor.fetchall()])
+ return tuple(_rowfactory(r, self.cursor)
+ for r in self.cursor.fetchall())
def var(self, *args):
return VariableWrapper(self.cursor.var(*args))
diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py
index 70c38c8de8..9e6e29d5e3 100644
--- a/django/db/backends/oracle/introspection.py
+++ b/django/db/backends/oracle/introspection.py
@@ -66,7 +66,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based.
"""
- return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))])
+ return dict((d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name)))
def get_relations(self, cursor, table_name):
"""
diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py
index 19bffc7520..d5c8d1006f 100644
--- a/django/db/backends/sqlite3/schema.py
+++ b/django/db/backends/sqlite3/schema.py
@@ -57,8 +57,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
field_maps = list(mapping.items())
self.execute("INSERT INTO %s (%s) SELECT %s FROM %s;" % (
self.quote_name(temp_model._meta.db_table),
- ', '.join([x for x, y in field_maps]),
- ', '.join([y for x, y in field_maps]),
+ ', '.join(x for x, y in field_maps),
+ ', '.join(y for x, y in field_maps),
self.quote_name(model._meta.db_table),
))
# Delete the old table
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
index 334c26d973..294f801435 100644
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -145,8 +145,8 @@ class MigrationAutodetector(object):
old_model_state = self.from_state.models[app_label, model_name]
new_model_state = self.to_state.models[app_label, model_name]
# New fields
- old_field_names = set([x for x, y in old_model_state.fields])
- new_field_names = set([x for x, y in new_model_state.fields])
+ old_field_names = set(x for x, y in old_model_state.fields)
+ new_field_names = set(x for x, y in new_model_state.fields)
for field_name in new_field_names - old_field_names:
field = new_model_state.get_field_by_name(field_name)
# Scan to see if this is actually a rename!
diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py
index 753aeacd04..75a44a8b95 100644
--- a/django/db/migrations/writer.py
+++ b/django/db/migrations/writer.py
@@ -104,7 +104,7 @@ class MigrationWriter(object):
imports.update(k_imports)
imports.update(v_imports)
strings.append((k_string, v_string))
- return "{%s}" % (", ".join(["%s: %s" % (k, v) for k, v in strings])), imports
+ return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports
# Datetimes
elif isinstance(value, (datetime.datetime, datetime.date)):
return repr(value), set(["import datetime"])
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 887381187d..259d597636 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -159,7 +159,7 @@ class ModelBase(type):
new_fields = new_class._meta.local_fields + \
new_class._meta.local_many_to_many + \
new_class._meta.virtual_fields
- field_names = set([f.name for f in new_fields])
+ field_names = set(f.name for f in new_fields)
# Basic setup for proxy models.
if is_proxy:
@@ -321,7 +321,7 @@ class ModelBase(type):
# Give the class a docstring -- its definition.
if cls.__doc__ is None:
- cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join([f.attname for f in opts.fields]))
+ cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.attname for f in opts.fields))
if hasattr(cls, 'get_absolute_url'):
cls.get_absolute_url = update_wrapper(curry(get_absolute_url, opts, cls.get_absolute_url),
diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py
index f4c64f7b7d..769e5b9bb6 100644
--- a/django/db/models/deletion.py
+++ b/django/db/models/deletion.py
@@ -234,8 +234,8 @@ class Collector(object):
found = True
if not found:
return
- self.data = OrderedDict([(model, self.data[model])
- for model in sorted_models])
+ self.data = OrderedDict((model, self.data[model])
+ for model in sorted_models)
def delete(self):
# sort instance collections
diff --git a/django/db/models/options.py b/django/db/models/options.py
index 5221468493..c89270eabb 100644
--- a/django/db/models/options.py
+++ b/django/db/models/options.py
@@ -320,7 +320,7 @@ class Options(object):
cache.append((field, model))
else:
cache.append((field, parent))
- cache.extend([(f, None) for f in self.local_fields])
+ cache.extend((f, None) for f in self.local_fields)
self._field_cache = tuple(cache)
self._field_name_cache = [x for x, _ in cache]
diff --git a/django/db/models/query.py b/django/db/models/query.py
index 5947a85730..5fb7edef00 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -1206,7 +1206,7 @@ class ValuesListQuerySet(ValuesQuerySet):
for row in self.query.get_compiler(self.db).results_iter():
data = dict(zip(names, row))
- yield tuple([data[f] for f in fields])
+ yield tuple(data[f] for f in fields)
def _clone(self, *args, **kwargs):
clone = super(ValuesListQuerySet, self)._clone(*args, **kwargs)
diff --git a/django/db/models/sql/aggregates.py b/django/db/models/sql/aggregates.py
index 9fc5fe8a5b..3cda4d244e 100644
--- a/django/db/models/sql/aggregates.py
+++ b/django/db/models/sql/aggregates.py
@@ -77,7 +77,7 @@ class Aggregate(object):
if hasattr(self.col, 'as_sql'):
field_name, params = self.col.as_sql(qn, connection)
elif isinstance(self.col, (list, tuple)):
- field_name = '.'.join([qn(c) for c in self.col])
+ field_name = '.'.join(qn(c) for c in self.col)
else:
field_name = self.col
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index 5dda379236..1c6e80b538 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -718,11 +718,11 @@ class SQLCompiler(object):
loaded_fields = self.query.get_loaded_field_names().get(self.query.model, set()) or self.query.select
aggregate_start = len(self.query.extra_select) + len(loaded_fields)
aggregate_end = aggregate_start + len(self.query.aggregate_select)
- row = tuple(row[:aggregate_start]) + tuple([
+ row = tuple(row[:aggregate_start]) + tuple(
self.query.resolve_aggregate(value, aggregate, self.connection)
for (alias, aggregate), value
in zip(self.query.aggregate_select.items(), row[aggregate_start:aggregate_end])
- ]) + tuple(row[aggregate_end:])
+ ) + tuple(row[aggregate_end:])
yield row
@@ -827,7 +827,7 @@ class SQLInsertCompiler(SQLCompiler):
has_fields = bool(self.query.fields)
fields = self.query.fields if has_fields else [opts.pk]
- result.append('(%s)' % ', '.join([qn(f.column) for f in fields]))
+ result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
if has_fields:
params = values = [
@@ -1007,7 +1007,7 @@ class SQLUpdateCompiler(SQLCompiler):
# selecting from the updating table (e.g. MySQL).
idents = []
for rows in query.get_compiler(self.using).execute_sql(MULTI):
- idents.extend([r[0] for r in rows])
+ idents.extend(r[0] for r in rows)
self.query.add_filter(('pk__in', idents))
self.query.related_ids = idents
else:
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 75d357ea15..93a0b52330 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -371,11 +371,11 @@ class Query(object):
if result is None:
result = [None for q in query.aggregate_select.items()]
- return dict([
+ return dict(
(alias, self.resolve_aggregate(val, aggregate, connection=connections[using]))
for (alias, aggregate), val
in zip(query.aggregate_select.items(), result)
- ])
+ )
def get_count(self, using):
"""
@@ -1755,7 +1755,7 @@ class Query(object):
"""
Callback used by get_deferred_field_names().
"""
- target[model] = set([f.name for f in fields])
+ target[model] = set(f.name for f in fields)
def set_aggregate_mask(self, names):
"Set the mask of aggregates that will actually be returned by the SELECT"
@@ -1790,10 +1790,10 @@ class Query(object):
if self._aggregate_select_cache is not None:
return self._aggregate_select_cache
elif self.aggregate_select_mask is not None:
- self._aggregate_select_cache = OrderedDict([
+ self._aggregate_select_cache = OrderedDict(
(k, v) for k, v in self.aggregates.items()
if k in self.aggregate_select_mask
- ])
+ )
return self._aggregate_select_cache
else:
return self.aggregates
@@ -1803,10 +1803,10 @@ class Query(object):
if self._extra_select_cache is not None:
return self._extra_select_cache
elif self.extra_select_mask is not None:
- self._extra_select_cache = OrderedDict([
+ self._extra_select_cache = OrderedDict(
(k, v) for k, v in self.extra.items()
if k in self.extra_select_mask
- ])
+ )
return self._extra_select_cache
else:
return self.extra
diff --git a/django/forms/fields.py b/django/forms/fields.py
index e995187682..8abb1b3513 100644
--- a/django/forms/fields.py
+++ b/django/forms/fields.py
@@ -874,8 +874,8 @@ class MultipleChoiceField(ChoiceField):
data = []
if len(initial) != len(data):
return True
- initial_set = set([force_text(value) for value in initial])
- data_set = set([force_text(value) for value in data])
+ initial_set = set(force_text(value) for value in initial)
+ data_set = set(force_text(value) for value in data)
return data_set != initial_set
diff --git a/django/forms/formsets.py b/django/forms/formsets.py
index 8a379ff3cf..e46a440480 100644
--- a/django/forms/formsets.py
+++ b/django/forms/formsets.py
@@ -380,17 +380,17 @@ class BaseFormSet(object):
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
- forms = ' '.join([form.as_table() for form in self])
+ forms = ' '.join(form.as_table() for form in self)
return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
def as_p(self):
"Returns this formset rendered as HTML
s."
- forms = ' '.join([form.as_p() for form in self])
+ forms = ' '.join(form.as_p() for form in self)
return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
def as_ul(self):
"Returns this formset rendered as HTML
s."
- forms = ' '.join([form.as_ul() for form in self])
+ forms = ' '.join(form.as_ul() for form in self)
return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
diff --git a/django/forms/models.py b/django/forms/models.py
index 9df97d6960..f292606862 100644
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1181,7 +1181,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
params={'pk': pk},
)
qs = self.queryset.filter(**{'%s__in' % key: value})
- pks = set([force_text(getattr(o, key)) for o in qs])
+ pks = set(force_text(getattr(o, key)) for o in qs)
for val in value:
if force_text(val) not in pks:
raise ValidationError(
@@ -1208,8 +1208,8 @@ class ModelMultipleChoiceField(ModelChoiceField):
data = []
if len(initial) != len(data):
return True
- initial_set = set([force_text(value) for value in self.prepare_value(initial)])
- data_set = set([force_text(value) for value in data])
+ initial_set = set(force_text(value) for value in self.prepare_value(initial))
+ data_set = set(force_text(value) for value in data)
return data_set != initial_set
diff --git a/django/forms/util.py b/django/forms/util.py
index 3c7724900a..320a74e721 100644
--- a/django/forms/util.py
+++ b/django/forms/util.py
@@ -49,7 +49,7 @@ class ErrorDict(dict):
))
def as_text(self):
- return '\n'.join(['* %s\n%s' % (k, '\n'.join([' * %s' % force_text(i) for i in v])) for k, v in self.items()])
+ return '\n'.join('* %s\n%s' % (k, '\n'.join(' * %s' % force_text(i) for i in v)) for k, v in self.items())
@python_2_unicode_compatible
class ErrorList(list):
@@ -69,7 +69,7 @@ class ErrorList(list):
def as_text(self):
if not self: return ''
- return '\n'.join(['* %s' % force_text(e) for e in self])
+ return '\n'.join('* %s' % force_text(e) for e in self)
def __repr__(self):
return repr([force_text(e) for e in self])
diff --git a/django/template/base.py b/django/template/base.py
index 382b85aefd..67af5b17f8 100644
--- a/django/template/base.py
+++ b/django/template/base.py
@@ -88,8 +88,8 @@ class VariableDoesNotExist(Exception):
self.params = params
def __str__(self):
- return self.msg % tuple([force_text(p, errors='replace')
- for p in self.params])
+ return self.msg % tuple(force_text(p, errors='replace')
+ for p in self.params)
class InvalidTemplateLibrary(Exception):
pass
@@ -1012,7 +1012,7 @@ def parse_bits(parser, bits, params, varargs, varkw, defaults,
# Some positional arguments were not supplied
raise TemplateSyntaxError(
"'%s' did not receive value(s) for the argument(s): %s" %
- (name, ", ".join(["'%s'" % p for p in unhandled_params])))
+ (name, ", ".join("'%s'" % p for p in unhandled_params)))
return args, kwargs
def generic_tag_compiler(parser, token, params, varargs, varkw, defaults,
diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
index 2a3af9b1eb..a7af7d7de8 100644
--- a/django/template/defaulttags.py
+++ b/django/template/defaulttags.py
@@ -205,7 +205,7 @@ class ForNode(Node):
# don't want to leave any vars from the previous loop on the
# context.
context.pop()
- return mark_safe(''.join([force_text(n) for n in nodelist]))
+ return mark_safe(''.join(force_text(n) for n in nodelist))
class IfChangedNode(Node):
child_nodelists = ('nodelist_true', 'nodelist_false')
@@ -410,8 +410,8 @@ class URLNode(Node):
def render(self, context):
from django.core.urlresolvers import reverse, NoReverseMatch
args = [arg.resolve(context) for arg in self.args]
- kwargs = dict([(smart_text(k, 'ascii'), v.resolve(context))
- for k, v in self.kwargs.items()])
+ kwargs = dict((smart_text(k, 'ascii'), v.resolve(context))
+ for k, v in self.kwargs.items())
view_name = self.view_name.resolve(context)
@@ -502,8 +502,8 @@ class WithNode(Node):
return ""
def render(self, context):
- values = dict([(key, val.resolve(context)) for key, val in
- six.iteritems(self.extra_context)])
+ values = dict((key, val.resolve(context)) for key, val in
+ six.iteritems(self.extra_context))
with context.push(**values):
return self.nodelist.render(context)
diff --git a/django/template/loader_tags.py b/django/template/loader_tags.py
index fafd9204a6..570366ea72 100644
--- a/django/template/loader_tags.py
+++ b/django/template/loader_tags.py
@@ -112,8 +112,8 @@ class ExtendsNode(Node):
# The ExtendsNode has to be the first non-text node.
if not isinstance(node, TextNode):
if not isinstance(node, ExtendsNode):
- blocks = dict([(n.name, n) for n in
- compiled_parent.nodelist.get_nodes_by_type(BlockNode)])
+ blocks = dict((n.name, n) for n in
+ compiled_parent.nodelist.get_nodes_by_type(BlockNode))
block_context.add_blocks(blocks)
break
diff --git a/django/test/_doctest.py b/django/test/_doctest.py
index 50d772cfad..6e8662afe5 100644
--- a/django/test/_doctest.py
+++ b/django/test/_doctest.py
@@ -598,7 +598,7 @@ class DocTestParser:
# If all lines begin with the same indentation, then strip it.
min_indent = self._min_indent(string)
if min_indent > 0:
- string = '\n'.join([l[min_indent:] for l in string.split('\n')])
+ string = '\n'.join(l[min_indent:] for l in string.split('\n'))
output = []
charno, lineno = 0, 0
@@ -670,7 +670,7 @@ class DocTestParser:
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
- source = '\n'.join([sl[indent+4:] for sl in source_lines])
+ source = '\n'.join(sl[indent+4:] for sl in source_lines)
# Divide want into lines; check that it's properly indented; and
# then strip the indentation. Spaces before the last newline should
@@ -681,7 +681,7 @@ class DocTestParser:
del want_lines[-1] # forget final newline & spaces after it
self._check_prefix(want_lines, ' '*indent, name,
lineno + len(source_lines))
- want = '\n'.join([wl[indent:] for wl in want_lines])
+ want = '\n'.join(wl[indent:] for wl in want_lines)
# If `want` contains a traceback message, then extract it.
m = self._EXCEPTION_RE.match(want)
diff --git a/django/utils/cache.py b/django/utils/cache.py
index 45f93b9b4c..7a77f911ce 100644
--- a/django/utils/cache.py
+++ b/django/utils/cache.py
@@ -76,7 +76,7 @@ def patch_cache_control(response, **kwargs):
for (k, v) in kwargs.items():
cc[k.replace('_', '-')] = v
- cc = ', '.join([dictvalue(el) for el in cc.items()])
+ cc = ', '.join(dictvalue(el) for el in cc.items())
response['Cache-Control'] = cc
def get_max_age(response):
@@ -86,8 +86,8 @@ def get_max_age(response):
"""
if not response.has_header('Cache-Control'):
return
- cc = dict([_to_tuple(el) for el in
- cc_delim_re.split(response['Cache-Control'])])
+ cc = dict(_to_tuple(el) for el in
+ cc_delim_re.split(response['Cache-Control']))
if 'max-age' in cc:
try:
return int(cc['max-age'])
@@ -144,7 +144,7 @@ def patch_vary_headers(response, newheaders):
else:
vary_headers = []
# Use .lower() here so we treat headers as case-insensitive.
- existing_headers = set([header.lower() for header in vary_headers])
+ existing_headers = set(header.lower() for header in vary_headers)
additional_headers = [newheader for newheader in newheaders
if newheader.lower() not in existing_headers]
response['Vary'] = ', '.join(vary_headers + additional_headers)
@@ -156,7 +156,7 @@ def has_vary_header(response, header_query):
if not response.has_header('Vary'):
return False
vary_headers = cc_delim_re.split(response['Vary'])
- existing_headers = set([header.lower() for header in vary_headers])
+ existing_headers = set(header.lower() for header in vary_headers)
return header_query.lower() in existing_headers
def _i18n_cache_key_suffix(request, cache_key):
diff --git a/django/utils/checksums.py b/django/utils/checksums.py
index 8617e22609..94c002967a 100644
--- a/django/utils/checksums.py
+++ b/django/utils/checksums.py
@@ -17,8 +17,8 @@ def luhn(candidate):
if not isinstance(candidate, six.string_types):
candidate = str(candidate)
try:
- evens = sum([int(c) for c in candidate[-1::-2]])
- odds = sum([LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2]])
+ evens = sum(int(c) for c in candidate[-1::-2])
+ odds = sum(LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2])
return ((evens + odds) % 10 == 0)
except ValueError: # Raised if an int conversion fails
return False
diff --git a/django/utils/crypto.py b/django/utils/crypto.py
index 15db972560..3c15b8b35b 100644
--- a/django/utils/crypto.py
+++ b/django/utils/crypto.py
@@ -73,7 +73,7 @@ def get_random_string(length=12,
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
- return ''.join([random.choice(allowed_chars) for i in range(length)])
+ return ''.join(random.choice(allowed_chars) for i in range(length))
def constant_time_compare(val1, val2):
diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
index 29228bd3a5..f4f694f399 100644
--- a/django/utils/datastructures.py
+++ b/django/utils/datastructures.py
@@ -231,7 +231,7 @@ class SortedDict(dict):
Replaces the normal dict.__repr__ with a version that returns the keys
in their sorted order.
"""
- return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in six.iteritems(self)])
+ return '{%s}' % ', '.join('%r: %r' % (k, v) for k, v in six.iteritems(self))
def clear(self):
super(SortedDict, self).clear()
diff --git a/django/utils/html.py b/django/utils/html.py
index 89e790d96f..46750d9cad 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -32,7 +32,7 @@ simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net
simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
link_target_attribute_re = re.compile(r'(]*?)target=[^\s>]+')
html_gunk_re = re.compile(r'(?: |<\/i>|<\/b>|<\/em>|<\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
-hard_coded_bullets_re = re.compile(r'((?: