diff --git a/django/contrib/admin/filters.py b/django/contrib/admin/filters.py index 1bdd6372242..380d80d9a33 100644 --- a/django/contrib/admin/filters.py +++ b/django/contrib/admin/filters.py @@ -293,8 +293,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 = {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/contenttypes/management.py b/django/contrib/contenttypes/management.py index 6da7c49ef5c..6255f0ca370 100644 --- a/django/contrib/contenttypes/management.py +++ b/django/contrib/contenttypes/management.py @@ -25,18 +25,18 @@ def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT app_label = app_config.label - app_models = dict( - (model._meta.model_name, model) - for model in app_config.get_models()) + app_models = { + model._meta.model_name: model + for model in app_config.get_models()} if not app_models: return # Get all the content types - content_types = dict( - (ct.model, ct) + content_types = { + ct.model: ct for ct in ContentType.objects.using(using).filter(app_label=app_label) - ) + } to_remove = [ ct for (model_name, ct) in six.iteritems(content_types) diff --git a/django/contrib/gis/gdal/field.py b/django/contrib/gis/gdal/field.py index dd60f3b9534..f9bc1f7a55e 100644 --- a/django/contrib/gis/gdal/field.py +++ b/django/contrib/gis/gdal/field.py @@ -216,4 +216,4 @@ OGRFieldTypes = { 10: OFTTime, 11: OFTDateTime, } -ROGRFieldTypes = dict((cls, num) for num, cls in OGRFieldTypes.items()) +ROGRFieldTypes = {cls: num for num, cls in OGRFieldTypes.items()} diff --git a/django/contrib/gis/gdal/geomtype.py b/django/contrib/gis/gdal/geomtype.py index 1b5e079ef89..dc1f0480a3f 100644 --- a/django/contrib/gis/gdal/geomtype.py +++ b/django/contrib/gis/gdal/geomtype.py @@ -28,7 +28,7 @@ class OGRGeomType(object): 7 + wkb25bit: 'GeometryCollection25D', } # Reverse type dictionary, keyed by lower-case of the name. - _str_types = dict((v.lower(), k) for k, v in _types.items()) + _str_types = {v.lower(): k for k, v in _types.items()} def __init__(self, type_input): "Figures out the correct OGR Type based upon the input." diff --git a/django/contrib/gis/gdal/libgdal.py b/django/contrib/gis/gdal/libgdal.py index 7bcf93f5189..65e58a3a33c 100644 --- a/django/contrib/gis/gdal/libgdal.py +++ b/django/contrib/gis/gdal/libgdal.py @@ -91,7 +91,7 @@ def gdal_version_info(): m = version_regex.match(ver) if not m: raise OGRException('Could not parse GDAL version string "%s"' % ver) - return dict((key, m.group(key)) for key in ('major', 'minor', 'subminor')) + return {key: m.group(key) for key in ('major', 'minor', 'subminor')} _verinfo = gdal_version_info() GDAL_MAJOR_VERSION = int(_verinfo['major']) diff --git a/django/contrib/gis/geoip/base.py b/django/contrib/gis/geoip/base.py index 08125e36150..9409019d940 100644 --- a/django/contrib/gis/geoip/base.py +++ b/django/contrib/gis/geoip/base.py @@ -48,7 +48,7 @@ class GeoIP(object): GEOIP_CHECK_CACHE = 2 GEOIP_INDEX_CACHE = 4 GEOIP_MMAP_CACHE = 8 - cache_options = dict((opt, None) for opt in (0, 1, 2, 4, 8)) + cache_options = {opt: None for opt in (0, 1, 2, 4, 8)} # Paths to the city & country binary databases. _city_file = '' diff --git a/django/contrib/gis/geoip/libgeoip.py b/django/contrib/gis/geoip/libgeoip.py index 73aa5fc9bf3..cc4d92c7d02 100644 --- a/django/contrib/gis/geoip/libgeoip.py +++ b/django/contrib/gis/geoip/libgeoip.py @@ -4,9 +4,9 @@ from ctypes.util import find_library from django.conf import settings # Creating the settings dictionary with any settings, if needed. -GEOIP_SETTINGS = dict((key, getattr(settings, key)) - for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY') - if hasattr(settings, key)) +GEOIP_SETTINGS = {key: getattr(settings, key) + for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY') + if hasattr(settings, key)} lib_path = GEOIP_SETTINGS.get('GEOIP_LIBRARY_PATH', None) # The shared library for the GeoIP C API. May be downloaded diff --git a/django/contrib/gis/geoip/prototypes.py b/django/contrib/gis/geoip/prototypes.py index 8ddcb9d974b..22c17f006fd 100644 --- a/django/contrib/gis/geoip/prototypes.py +++ b/django/contrib/gis/geoip/prototypes.py @@ -58,7 +58,7 @@ def check_record(result, func, cargs): # Checking the pointer to the C structure, if valid pull out elements # into a dictionary. rec = result.contents - record = dict((fld, getattr(rec, fld)) for fld, ctype in rec._fields_) + record = {fld: getattr(rec, fld) for fld, ctype in rec._fields_} # Now converting the strings to unicode using the proper encoding. encoding = geoip_encodings[record['charset']] diff --git a/django/contrib/gis/geometry/test_data.py b/django/contrib/gis/geometry/test_data.py index 3ad2f4aaea1..d6a8bf8263b 100644 --- a/django/contrib/gis/geometry/test_data.py +++ b/django/contrib/gis/geometry/test_data.py @@ -24,7 +24,7 @@ def tuplize(seq): def strconvert(d): "Converts all keys in dictionary to str type." - return dict((str(k), v) for k, v in six.iteritems(d)) + return {str(k): v for k, v in six.iteritems(d)} def get_ds_file(name, ext): diff --git a/django/contrib/gis/geos/libgeos.py b/django/contrib/gis/geos/libgeos.py index e503bbd3e6e..207fa780a4d 100644 --- a/django/contrib/gis/geos/libgeos.py +++ b/django/contrib/gis/geos/libgeos.py @@ -145,8 +145,8 @@ def geos_version_info(): m = version_regex.match(ver) if not m: raise GEOSException('Could not parse version info string "%s"' % ver) - return dict((key, m.group(key)) for key in ( - 'version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor')) + return {key: m.group(key) for key in ( + 'version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor')} # Version numbers and whether or not prepared geometry support is available. _verinfo = geos_version_info() diff --git a/django/contrib/gis/management/commands/ogrinspect.py b/django/contrib/gis/management/commands/ogrinspect.py index 01930ff047d..2e53eda6adc 100644 --- a/django/contrib/gis/management/commands/ogrinspect.py +++ b/django/contrib/gis/management/commands/ogrinspect.py @@ -90,8 +90,8 @@ class Command(BaseCommand): # and options. from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping # Filter options to params accepted by `_ogrinspect` - ogr_options = dict((k, v) for k, v in options.items() - if k in inspect.getargspec(_ogrinspect).args and v is not None) + ogr_options = {k: v for k, v in options.items() + if k in inspect.getargspec(_ogrinspect).args and v is not None} output = [s for s in _ogrinspect(ds, model_name, **ogr_options)] if options['mapping']: @@ -104,7 +104,7 @@ class Command(BaseCommand): mapping_dict = mapping(ds, **kwargs) # This extra legwork is so that the dictionary definition comes # out in the same order as the fields in the model definition. - rev_mapping = dict((v, k) for k, v in mapping_dict.items()) + rev_mapping = {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'," % ( diff --git a/django/contrib/gis/measure.py b/django/contrib/gis/measure.py index 456f1c72774..90b316bb603 100644 --- a/django/contrib/gis/measure.py +++ b/django/contrib/gis/measure.py @@ -295,7 +295,7 @@ class Distance(MeasureBase): 'Yard (Indian)': 'indian_yd', 'Yard (Sears)': 'sears_yd' } - LALIAS = dict((k.lower(), v) for k, v in ALIAS.items()) + LALIAS = {k.lower(): v for k, v in ALIAS.items()} def __mul__(self, other): if isinstance(other, self.__class__): @@ -313,9 +313,9 @@ class Distance(MeasureBase): class Area(MeasureBase): STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT # Getting the square units values and the alias dictionary. - UNITS = dict(('%s%s' % (AREA_PREFIX, k), v ** 2) for k, v in Distance.UNITS.items()) - ALIAS = dict((k, '%s%s' % (AREA_PREFIX, v)) for k, v in Distance.ALIAS.items()) - LALIAS = dict((k.lower(), v) for k, v in ALIAS.items()) + UNITS = {'%s%s' % (AREA_PREFIX, k): v ** 2 for k, v in Distance.UNITS.items()} + ALIAS = {k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()} + LALIAS = {k.lower(): v for k, v in ALIAS.items()} def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): diff --git a/django/contrib/gis/tests/geo3d/tests.py b/django/contrib/gis/tests/geo3d/tests.py index 47c141a2ac9..740f0d56925 100644 --- a/django/contrib/gis/tests/geo3d/tests.py +++ b/django/contrib/gis/tests/geo3d/tests.py @@ -38,7 +38,7 @@ city_data = ( ) # Reference mapping of city name to its altitude (Z value). -city_dict = dict((name, coords) for name, coords in city_data) +city_dict = {name: coords for name, coords in city_data} # 3D freeway data derived from the National Elevation Dataset: # http://seamless.usgs.gov/products/9arc.php diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index 49a5f5f2745..5031aadab8f 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -329,7 +329,7 @@ class LayerMapping(object): if isinstance(self.unique, six.string_types): return {self.unique: kwargs[self.unique]} else: - return dict((fld, kwargs[fld]) for fld in self.unique) + return {fld: kwargs[fld] for fld in self.unique} #### Verification routines used in constructing model keyword arguments. #### def verify_ogr_field(self, ogr_field, model_field): diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py index 02f13597dce..71eee0cdfa8 100644 --- a/django/contrib/messages/storage/cookie.py +++ b/django/contrib/messages/storage/cookie.py @@ -41,8 +41,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 {key: self.process_messages(value) + for key, value in six.iteritems(obj)} return obj def decode(self, s, **kwargs): diff --git a/django/contrib/messages/tests/base.py b/django/contrib/messages/tests/base.py index 9c8745784b5..13b6fa0a3ab 100644 --- a/django/contrib/messages/tests/base.py +++ b/django/contrib/messages/tests/base.py @@ -207,7 +207,7 @@ class BaseTests(object): show_url = reverse('show_message') messages = [] for level in ('debug', 'info', 'success', 'warning', 'error'): - messages.extend([Message(self.levels[level], msg) for msg in data['messages']]) + messages.extend(Message(self.levels[level], msg) for msg in data['messages']) add_url = reverse('add_message', args=(level,)) self.client.post(add_url, data) response = self.client.get(show_url) diff --git a/django/contrib/postgres/forms/array.py b/django/contrib/postgres/forms/array.py index 620c7c7b6e0..0bd4ee49164 100644 --- a/django/contrib/postgres/forms/array.py +++ b/django/contrib/postgres/forms/array.py @@ -26,7 +26,7 @@ class SimpleArrayField(forms.CharField): def prepare_value(self, value): if isinstance(value, list): - return self.delimiter.join([six.text_type(self.base_field.prepare_value(v)) for v in value]) + return self.delimiter.join(six.text_type(self.base_field.prepare_value(v)) for v in value) return value def to_python(self, value): diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index 047e822e1a4..55a88df178c 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -103,9 +103,9 @@ def call_command(name, *args, **options): parser = command.create_parser('', name) if command.use_argparse: # Use the `dest` option name from the parser option - opt_mapping = dict((sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'), s_opt.dest) - for s_opt in parser._actions if s_opt.option_strings) - arg_options = dict((opt_mapping.get(key, key), value) for key, value in options.items()) + opt_mapping = {sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'): s_opt.dest + for s_opt in parser._actions if s_opt.option_strings} + arg_options = {opt_mapping.get(key, key): value for key, value in options.items()} defaults = parser.parse_args(args=args) defaults = dict(defaults._get_kwargs(), **arg_options) # Move positional args out of options to mimic legacy optparse @@ -237,25 +237,25 @@ class ManagementUtility(object): # 'key=value' pairs if cwords[0] == 'runfcgi': from django.core.servers.fastcgi import FASTCGI_OPTIONS - options += [(k, 1) for k in FASTCGI_OPTIONS] + options.extend((k, 1) for k in FASTCGI_OPTIONS) # special case: add the names of installed apps to options elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear', 'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'): try: app_configs = apps.get_app_configs() # Get the last part of the dotted path as the app name. - options += [(app_config.label, 0) for app_config in app_configs] + options.extend((app_config.label, 0) for app_config in app_configs) except ImportError: # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # user will find out once they execute the command. pass parser = subcommand_cls.create_parser('', cwords[0]) if subcommand_cls.use_argparse: - options += [(sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in - parser._actions if s_opt.option_strings] + options.extend((sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in + parser._actions if s_opt.option_strings) else: - options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in - parser.option_list] + options.extend((s_opt.get_opt_string(), s_opt.nargs) for s_opt in + parser.option_list) # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [opt for opt in options if opt[0] not in prev_opts] diff --git a/django/core/management/base.py b/django/core/management/base.py index 5fe50bd71af..68bcb188e56 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -58,7 +58,7 @@ class CommandParser(ArgumentParser): def parse_args(self, args=None, namespace=None): # Catch missing argument for a better error message if (hasattr(self.cmd, 'missing_args_message') and - not (args or any([not arg.startswith('-') for arg in args]))): + not (args or any(not arg.startswith('-') for arg in args))): self.error(self.cmd.missing_args_message) return super(CommandParser, self).parse_args(args, namespace) diff --git a/django/core/management/commands/compilemessages.py b/django/core/management/commands/compilemessages.py index 26ceb19261b..dbadac0c7dc 100644 --- a/django/core/management/commands/compilemessages.py +++ b/django/core/management/commands/compilemessages.py @@ -60,7 +60,7 @@ class Command(BaseCommand): basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings - basedirs.extend([upath(path) for path in settings.LOCALE_PATHS]) + basedirs.extend(upath(path) for path in settings.LOCALE_PATHS) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) diff --git a/django/core/management/commands/diffsettings.py b/django/core/management/commands/diffsettings.py index ac724fca3fd..9729131b3f3 100644 --- a/django/core/management/commands/diffsettings.py +++ b/django/core/management/commands/diffsettings.py @@ -3,7 +3,7 @@ from django.core.management.base import BaseCommand def module_to_dict(module, omittable=lambda k: k.startswith('_')): """Converts a module namespace to a Python dictionary.""" - return dict((k, repr(v)) for k, v in module.__dict__.items() if not omittable(k)) + return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)} class Command(BaseCommand): diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index 32ee23581d9..bc8d3be2f5d 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -134,9 +134,9 @@ class Command(BaseCommand): if extra_params: if not field_desc.endswith('('): field_desc += ', ' - field_desc += ', '.join([ + field_desc += ', '.join( '%s=%s' % (k, strip_prefix(repr(v))) - for k, v in extra_params.items()]) + for k, v in extra_params.items()) field_desc += ')' if comment_notes: field_desc += ' # ' + ' '.join(comment_notes) diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py index bc78ff5f846..8cce2fae76f 100644 --- a/django/core/management/commands/makemigrations.py +++ b/django/core/management/commands/makemigrations.py @@ -66,10 +66,10 @@ class Command(BaseCommand): # If app_labels is specified, filter out conflicting migrations for unspecified apps if app_labels: - conflicts = dict( - (app_label, conflict) for app_label, conflict in iteritems(conflicts) + conflicts = { + app_label: conflict for app_label, conflict in iteritems(conflicts) if app_label in app_labels - ) + } if conflicts and not self.merge: name_str = "; ".join( @@ -103,10 +103,10 @@ class Command(BaseCommand): if not app_labels: raise CommandError("You must supply at least one app label when using --empty.") # Make a fake changes() result we can pass to arrange_for_graph - changes = dict( - (app, [Migration("custom", app)]) + changes = { + app: [Migration("custom", app)] for app in app_labels - ) + } changes = autodetector.arrange_for_graph( changes=changes, graph=loader.graph, @@ -224,7 +224,7 @@ class Command(BaseCommand): for migration in merge_migrations ] try: - biggest_number = max([x for x in numbers if x is not None]) + biggest_number = max(x for x in numbers if x is not None) except ValueError: biggest_number = 1 subclass = type("Migration", (Migration, ), { diff --git a/django/core/management/sql.py b/django/core/management/sql.py index 275711a3850..955d8391b3e 100644 --- a/django/core/management/sql.py +++ b/django/core/management/sql.py @@ -62,8 +62,8 @@ def sql_create(app_config, style, connection): if not_installed_models: alter_sql = [] for model in not_installed_models: - alter_sql.extend(['-- ' + sql for sql in - connection.creation.sql_for_pending_references(model, style, pending_references)]) + alter_sql.extend('-- ' + sql for sql in + connection.creation.sql_for_pending_references(model, style, pending_references)) if alter_sql: final_output.append('-- The following references should be added but depend on non-existent tables:') final_output.extend(alter_sql) diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py index 62e3949df84..d7383a04227 100644 --- a/django/core/urlresolvers.py +++ b/django/core/urlresolvers.py @@ -428,7 +428,7 @@ class RegexURLResolver(LocaleRegexProvider): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") text_args = [force_text(v) for v in args] - text_kwargs = dict((k, force_text(v)) for (k, v) in kwargs.items()) + text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()} if not self._populated: self._populate() diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index dc4205e8561..fcdb742f85d 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -918,7 +918,7 @@ class BaseDatabaseOperations(object): elif params is None: u_params = () else: - u_params = dict((to_unicode(k), to_unicode(v)) for k, v in params.items()) + u_params = {to_unicode(k): to_unicode(v) for k, v in params.items()} return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params) @@ -1302,8 +1302,8 @@ class BaseDatabaseIntrospection(object): in sorting order between databases. """ def get_names(cursor): - return sorted([ti.name for ti in self.get_table_list(cursor) - if include_views or ti.type == 't']) + return sorted(ti.name for ti in self.get_table_list(cursor) + if include_views or ti.type == 't') if cursor is None: with self.connection.cursor() as cursor: return get_names(cursor) diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py index e60d12768ae..d11b0bee470 100644 --- a/django/db/backends/mysql/introspection.py +++ b/django/db/backends/mysql/introspection.py @@ -62,7 +62,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, extra FROM information_schema.columns WHERE table_name = %s AND table_schema = DATABASE()""", [table_name]) - field_info = dict((line[0], InfoLine(*line)) for line in cursor.fetchall()) + field_info = {line[0]: InfoLine(*line) for line in cursor.fetchall()} cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)) to_int = lambda i: int(i) if i is not None else i @@ -85,7 +85,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 {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 aa970229316..8f025ef41e0 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -886,7 +886,7 @@ class FormatStylePlaceholderCursor(object): def _format_params(self, params): try: - return dict((k, OracleParam(v, self, True)) for k, v in params.items()) + return {k: OracleParam(v, self, True) for k, v in params.items()} except AttributeError: return tuple(OracleParam(p, self, True) for p in params) @@ -911,7 +911,7 @@ class FormatStylePlaceholderCursor(object): def _param_generator(self, params): # Try dict handling; if that fails, treat as sequence if hasattr(params, 'items'): - return dict((k, v.force_bytes) for k, v in params.items()) + return {k: v.force_bytes for k, v in params.items()} else: return [p.force_bytes for p in params] @@ -927,7 +927,7 @@ class FormatStylePlaceholderCursor(object): query = convert_unicode(query, self.charset) elif hasattr(params, 'keys'): # Handle params as dict - args = dict((k, ":%s" % k) for k in params.keys()) + args = {k: ":%s" % k for k in params.keys()} query = convert_unicode(query % args, self.charset) else: # Handle params as sequence diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py index 37ed7e1f001..a16a021867f 100644 --- a/django/db/backends/oracle/introspection.py +++ b/django/db/backends/oracle/introspection.py @@ -74,7 +74,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 {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/postgresql_psycopg2/introspection.py b/django/db/backends/postgresql_psycopg2/introspection.py index aa9ab85a4d3..4ff155f572b 100644 --- a/django/db/backends/postgresql_psycopg2/introspection.py +++ b/django/db/backends/postgresql_psycopg2/introspection.py @@ -61,7 +61,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): SELECT column_name, is_nullable, column_default FROM information_schema.columns WHERE table_name = %s""", [table_name]) - field_map = dict((line[0], line[1:]) for line in cursor.fetchall()) + field_map = {line[0]: 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]),) + line[1:6] + (field_map[force_text(line[0])][0] == 'YES', field_map[force_text(line[0])][1]))) diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index 40efa822b1d..0ac2f25e04d 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -49,10 +49,10 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): Shortcut to transform a model from old_model into new_model """ # Work out the new fields dict / mapping - body = dict((f.name, f) for f in model._meta.local_fields) + body = {f.name: f for f in model._meta.local_fields} # Since mapping might mix column names and default values, # its values must be already quoted. - mapping = dict((f.column, self.quote_name(f.column)) for f in model._meta.local_fields) + mapping = {f.column: self.quote_name(f.column) for f in model._meta.local_fields} # This maps field names (not columns) for things like unique_together rename_mapping = {} # If any of the new or altered fields is introducing a new PK, diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index 4f3dfe9846f..eab34454a20 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -63,10 +63,10 @@ class MigrationAutodetector(object): return ( path, [self.deep_deconstruct(value) for value in args], - dict( - (key, self.deep_deconstruct(value)) + { + key: self.deep_deconstruct(value) for key, value in kwargs.items() - ), + }, ) def only_relation_agnostic_fields(self, fields): diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py index 5d62e2fb10f..9cc428e1622 100644 --- a/django/db/migrations/loader.py +++ b/django/db/migrations/loader.py @@ -315,7 +315,7 @@ class MigrationLoader(object): if app_label in seen_apps: conflicting_apps.add(app_label) seen_apps.setdefault(app_label, set()).add(migration_name) - return dict((app_label, seen_apps[app_label]) for app_label in conflicting_apps) + return {app_label: seen_apps[app_label] for app_label in conflicting_apps} def project_state(self, nodes=None, at_end=True): """ diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index 39da247eca8..b13e59c2218 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -35,7 +35,7 @@ class ProjectState(object): def clone(self): "Returns an exact copy of this ProjectState" return ProjectState( - models=dict((k, v.clone()) for k, v in self.models.items()), + models={k: v.clone() for k, v in self.models.items()}, real_apps=self.real_apps, ) @@ -271,10 +271,10 @@ class ModelState(object): elif isinstance(value, set): return set(cls.force_text_recursive(x) for x in value) elif isinstance(value, dict): - return dict( - (cls.force_text_recursive(k), cls.force_text_recursive(v)) + return { + cls.force_text_recursive(k): cls.force_text_recursive(v) for k, v in value.items() - ) + } return value def construct_fields(self): diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py index dec0eae33df..2e7afbd6637 100644 --- a/django/db/migrations/writer.py +++ b/django/db/migrations/writer.py @@ -141,7 +141,7 @@ class MigrationWriter(object): imports.add("from django.conf import settings") else: # No need to output bytestrings for dependencies - dependency = tuple([force_text(s) for s in dependency]) + dependency = tuple(force_text(s) for s in dependency) dependencies.append(" %s," % self.serialize(dependency)[0]) items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else "" diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 04189ad0972..a3e4a1d9eba 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -405,7 +405,7 @@ class SingleRelatedObjectDescriptor(object): rel_obj_attr = attrgetter(self.related.field.attname) instance_attr = lambda obj: obj._get_pk_val() - instances_dict = dict((instance_attr(inst), inst) for inst in instances) + instances_dict = {instance_attr(inst): inst for inst in instances} query = {'%s__in' % self.related.field.name: instances} queryset = queryset.filter(**query) @@ -536,7 +536,7 @@ class ReverseSingleRelatedObjectDescriptor(object): rel_obj_attr = self.field.get_foreign_related_value instance_attr = self.field.get_local_related_value - instances_dict = dict((instance_attr(inst), inst) for inst in instances) + instances_dict = {instance_attr(inst): inst for inst in instances} related_field = self.field.foreign_related_fields[0] # FIXME: This will need to be revisited when we introduce support for @@ -570,9 +570,9 @@ class ReverseSingleRelatedObjectDescriptor(object): if None in val: rel_obj = None else: - params = dict( - (rh_field.attname, getattr(instance, lh_field.attname)) - for lh_field, rh_field in self.field.related_fields) + params = { + rh_field.attname: getattr(instance, lh_field.attname) + for lh_field, rh_field in self.field.related_fields} qs = self.get_queryset(instance=instance) extra_filter = self.field.get_extra_descriptor_filter(instance) if isinstance(extra_filter, dict): @@ -702,7 +702,7 @@ def create_foreign_related_manager(superclass, rel_field, rel_model): rel_obj_attr = rel_field.get_local_related_value instance_attr = rel_field.get_foreign_related_value - instances_dict = dict((instance_attr(inst), inst) for inst in instances) + instances_dict = {instance_attr(inst): inst for inst in instances} query = {'%s__in' % rel_field.name: instances} queryset = queryset.filter(**query) @@ -927,9 +927,9 @@ def create_many_related_manager(superclass, rel): join_table = self.through._meta.db_table connection = connections[queryset.db] qn = connection.ops.quote_name - queryset = queryset.extra(select=dict( - ('_prefetch_related_val_%s' % f.attname, - '%s.%s' % (qn(join_table), qn(f.column))) for f in fk.local_related_fields)) + queryset = queryset.extra(select={ + '_prefetch_related_val_%s' % f.attname: + '%s.%s' % (qn(join_table), qn(f.column)) for f in fk.local_related_fields}) return ( queryset, lambda result: tuple( diff --git a/django/db/models/query.py b/django/db/models/query.py index 6ab41dc21ce..6e6d1abf3fa 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -491,7 +491,7 @@ class QuerySet(object): for f in self.model._meta.fields: if f.attname in lookup: lookup[f.name] = lookup.pop(f.attname) - params = dict((k, v) for k, v in kwargs.items() if LOOKUP_SEP not in k) + params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k} params.update(defaults) return lookup, params @@ -545,7 +545,7 @@ class QuerySet(object): if not id_list: return {} qs = self.filter(pk__in=id_list).order_by() - return dict((obj._get_pk_val(), obj) for obj in qs) + return {obj._get_pk_val(): obj for obj in qs} def delete(self): """ diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py index 0fbe25cca7a..bb1c52efd4d 100644 --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -205,7 +205,7 @@ def deferred_class_factory(model, attrs): proxy = True app_label = model._meta.app_label - overrides = dict((attr, DeferredAttribute(attr, model)) for attr in attrs) + overrides = {attr: DeferredAttribute(attr, model) for attr in attrs} overrides["Meta"] = Meta overrides["__module__"] = model.__module__ overrides["_deferred"] = True diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index dadca181294..cad6372eea2 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -377,7 +377,7 @@ class Query(object): inner_query.select_related = False inner_query.related_select_cols = [] - relabels = dict((t, 'subquery') for t in inner_query.tables) + relabels = {t: 'subquery' for t in inner_query.tables} relabels[None] = 'subquery' # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. @@ -390,10 +390,10 @@ class Query(object): try: outer_query.add_subquery(inner_query, using) except EmptyResultSet: - return dict( - (alias, None) + return { + alias: None for alias in outer_query.annotation_select - ) + } else: outer_query = self self.select = [] @@ -421,11 +421,11 @@ class Query(object): converters[position] = ([], [annotation.convert_value], annotation.output_field) result = compiler.apply_converters(result, converters) - return dict( - (alias, val) + return { + alias: val for (alias, annotation), val in zip(outer_query.annotation_select.items(), result) - ) + } def get_count(self, using): """ diff --git a/django/forms/fields.py b/django/forms/fields.py index 950f9481a3d..7ca8ddc2e2c 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -1028,7 +1028,7 @@ class MultiValueField(Field): def __deepcopy__(self, memo): result = super(MultiValueField, self).__deepcopy__(memo) - result.fields = tuple([x.__deepcopy__(memo) for x in self.fields]) + result.fields = tuple(x.__deepcopy__(memo) for x in self.fields) return result def validate(self, value): diff --git a/django/forms/models.py b/django/forms/models.py index 42c62d57702..7ca49543586 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -567,7 +567,7 @@ class BaseModelFormSet(BaseFormSet): def _existing_object(self, pk): if not hasattr(self, '_object_dict'): - self._object_dict = dict((o.pk, o) for o in self.get_queryset()) + self._object_dict = {o.pk: o for o in self.get_queryset()} return self._object_dict.get(pk) def _get_to_python(self, field): diff --git a/django/http/request.py b/django/http/request.py index 0f085d57d59..ea32574c689 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -458,8 +458,8 @@ class QueryDict(MultiValueDict): encode = lambda k, v: urlencode({k: v}) for k, list_ in self.lists(): k = force_bytes(k, self.encoding) - output.extend([encode(k, force_bytes(v, self.encoding)) - for v in list_]) + output.extend(encode(k, force_bytes(v, self.encoding)) + for v in list_) return '&'.join(output) diff --git a/django/template/base.py b/django/template/base.py index 22e411270d0..8a9099baa58 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -1058,7 +1058,7 @@ class TagHelperNode(Node): resolved_args = [var.resolve(context) for var in self.args] if self.takes_context: resolved_args = [context] + resolved_args - resolved_kwargs = dict((k, v.resolve(context)) for k, v in self.kwargs.items()) + resolved_kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()} return resolved_args, resolved_kwargs @@ -1301,9 +1301,9 @@ def get_templatetags_modules(): Caches the result for faster access. """ templatetags_modules_candidates = ['django.templatetags'] - templatetags_modules_candidates += [ + templatetags_modules_candidates.extend( '%s.templatetags' % app_config.name - for app_config in apps.get_app_configs()] + for app_config in apps.get_app_configs()) templatetags_modules = [] for templatetag_module in templatetags_modules_candidates: diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index c6814983e7c..405de785e80 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -562,8 +562,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 = {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 e758990c726..5bd0d274286 100644 --- a/django/template/loader_tags.py +++ b/django/template/loader_tags.py @@ -86,7 +86,7 @@ class ExtendsNode(Node): self.nodelist = nodelist self.parent_name = parent_name self.template_dirs = template_dirs - self.blocks = dict((n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)) + self.blocks = {n.name: n for n in nodelist.get_nodes_by_type(BlockNode)} def __repr__(self): return '' % self.parent_name.token @@ -120,8 +120,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 = {n.name: n for n in + compiled_parent.nodelist.get_nodes_by_type(BlockNode)} block_context.add_blocks(blocks) break diff --git a/django/templatetags/i18n.py b/django/templatetags/i18n.py index d9db91a4132..0bfb4a9eff2 100644 --- a/django/templatetags/i18n.py +++ b/django/templatetags/i18n.py @@ -158,7 +158,7 @@ class BlockTranslateNode(Node): val = default_value % key if '%s' in default_value else default_value return render_value_in_context(val, context) - data = dict((v, render_value(v)) for v in vars) + data = {v: render_value(v) for v in vars} context.pop() try: result = result % data diff --git a/django/test/client.py b/django/test/client.py index 62f7c5fb6c5..a19970f02e3 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -172,19 +172,19 @@ def encode_multipart(boundary, data): if is_file(item): lines.extend(encode_file(boundary, key, item)) else: - lines.extend([to_bytes(val) for val in [ + lines.extend(to_bytes(val) for val in [ '--%s' % boundary, 'Content-Disposition: form-data; name="%s"' % key, '', item - ]]) + ]) else: - lines.extend([to_bytes(val) for val in [ + lines.extend(to_bytes(val) for val in [ '--%s' % boundary, 'Content-Disposition: form-data; name="%s"' % key, '', value - ]]) + ]) lines.extend([ to_bytes('--%s--' % boundary), diff --git a/django/test/utils.py b/django/test/utils.py index 3d9a0d35267..dff9c4e25b6 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -309,8 +309,8 @@ def compare_xml(want, got): return _norm_whitespace_re.sub(' ', v) def child_text(element): - return ''.join([c.data for c in element.childNodes - if c.nodeType == Node.TEXT_NODE]) + return ''.join(c.data for c in element.childNodes + if c.nodeType == Node.TEXT_NODE) def children(element): return [c for c in element.childNodes diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index 49fd9d98484..58108faa4b7 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -346,7 +346,7 @@ class MultiValueDict(dict): def __getstate__(self): obj_dict = self.__dict__.copy() - obj_dict['_data'] = dict((k, self.getlist(k)) for k in self) + obj_dict['_data'] = {k: self.getlist(k) for k in self} return obj_dict def __setstate__(self, obj_dict): @@ -467,7 +467,7 @@ class MultiValueDict(dict): """ Returns current object as a dict with singular values. """ - return dict((key, self[key]) for key in self) + return {key: self[key] for key in self} class ImmutableList(tuple): diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py index cb45a2760b1..422f55b9c54 100644 --- a/django/utils/dateparse.py +++ b/django/utils/dateparse.py @@ -36,7 +36,7 @@ def parse_date(value): """ match = date_re.match(value) if match: - kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict())) + kw = {k: int(v) for k, v in six.iteritems(match.groupdict())} return datetime.date(**kw) @@ -54,7 +54,7 @@ def parse_time(value): kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') - kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None) + kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None} return datetime.time(**kw) @@ -81,6 +81,6 @@ def parse_datetime(value): if tzinfo[0] == '-': offset = -offset tzinfo = get_fixed_timezone(offset) - kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None) + kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None} kw['tzinfo'] = tzinfo return datetime.datetime(**kw) diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py index e2c7a43c442..16446279673 100644 --- a/django/utils/dictconfig.py +++ b/django/utils/dictconfig.py @@ -264,7 +264,7 @@ class BaseConfigurator(object): c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers - kwargs = dict((k, config[k]) for k in config if valid_ident(k)) + kwargs = {k: config[k] for k in config if valid_ident(k)} result = c(**kwargs) if props: for name, value in props.items(): @@ -502,7 +502,7 @@ class DictConfigurator(BaseConfigurator): 'address' in config: config['address'] = self.as_tuple(config['address']) factory = klass - kwargs = dict((k, config[k]) for k in config if valid_ident(k)) + kwargs = {k: config[k] for k in config if valid_ident(k)} try: result = factory(**kwargs) except TypeError as te: diff --git a/django/utils/encoding.py b/django/utils/encoding.py index 39d548a9cef..40096741a7f 100644 --- a/django/utils/encoding.py +++ b/django/utils/encoding.py @@ -105,8 +105,8 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'): # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. - s = ' '.join([force_text(arg, encoding, strings_only, - errors) for arg in s]) + s = ' '.join(force_text(arg, encoding, strings_only, errors) + for arg in s) return s @@ -152,8 +152,8 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. - return b' '.join([force_bytes(arg, encoding, strings_only, - errors) for arg in s]) + return b' '.join(force_bytes(arg, encoding, strings_only, errors) + for arg in s) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors) diff --git a/django/utils/html.py b/django/utils/html.py index 1247849f31b..3c03210c110 100644 --- a/django/utils/html.py +++ b/django/utils/html.py @@ -90,7 +90,7 @@ def format_html(format_string, *args, **kwargs): of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditional_escape, args) - kwargs_safe = dict((k, conditional_escape(v)) for (k, v) in six.iteritems(kwargs)) + kwargs_safe = {k: conditional_escape(v) for (k, v) in six.iteritems(kwargs)} return mark_safe(format_string.format(*args_safe, **kwargs_safe)) diff --git a/django/utils/termcolors.py b/django/utils/termcolors.py index aa2cdc97c33..47bce5244c8 100644 --- a/django/utils/termcolors.py +++ b/django/utils/termcolors.py @@ -5,8 +5,8 @@ termcolors.py from django.utils import six color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') -foreground = dict((color_names[x], '3%s' % x) for x in range(8)) -background = dict((color_names[x], '4%s' % x) for x in range(8)) +foreground = {color_names[x]: '3%s' % x for x in range(8)} +background = {color_names[x]: '4%s' % x for x in range(8)} RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} diff --git a/django/utils/tree.py b/django/utils/tree.py index eceaf20ebaa..a8d96893b0e 100644 --- a/django/utils/tree.py +++ b/django/utils/tree.py @@ -43,10 +43,10 @@ class Node(object): def __str__(self): if self.negated: - return '(NOT (%s: %s))' % (self.connector, ', '.join([str(c) for c - in self.children])) - return '(%s: %s)' % (self.connector, ', '.join([str(c) for c in - self.children])) + return '(NOT (%s: %s))' % (self.connector, ', '.join(str(c) for c + in self.children)) + return '(%s: %s)' % (self.connector, ', '.join(str(c) for c in + self.children)) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) diff --git a/django/views/debug.py b/django/views/debug.py index 55f9b231eaf..09cc5c462ef 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -59,7 +59,7 @@ def cleanse_setting(key, value): cleansed = CLEANSED_SUBSTITUTE else: if isinstance(value, dict): - cleansed = dict((k, cleanse_setting(k, v)) for k, v in value.items()) + cleansed = {k: cleanse_setting(k, v) for k, v in value.items()} else: cleansed = value except TypeError: diff --git a/docs/_ext/applyxrefs.py b/docs/_ext/applyxrefs.py index e9ba0fdd63a..513c17d84ec 100644 --- a/docs/_ext/applyxrefs.py +++ b/docs/_ext/applyxrefs.py @@ -53,7 +53,7 @@ def main(argv=None): files = [] for root in argv[1:]: for (dirpath, dirnames, filenames) in os.walk(root): - files.extend([(dirpath, f) for f in filenames]) + files.extend((dirpath, f) for f in filenames) files.sort() files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')] #print files diff --git a/docs/_ext/literals_to_xrefs.py b/docs/_ext/literals_to_xrefs.py index 41ae8112922..c3bd2628e8a 100644 --- a/docs/_ext/literals_to_xrefs.py +++ b/docs/_ext/literals_to_xrefs.py @@ -145,8 +145,8 @@ def colorize(text='', opts=(), **kwargs): print('this should not be red') """ color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') - foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) - background = dict([(color_names[x], '4%s' % x) for x in range(8)]) + foreground = {color_names[x]: '3%s' % x for x in range(8)} + background = {color_names[x]: '4%s' % x for x in range(8)} RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index 2bd24357cfe..6784f352ed8 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -882,8 +882,8 @@ For example, suppose you have these models:: toppings = models.ManyToManyField(Topping) def __str__(self): # __unicode__ on Python 2 - return "%s (%s)" % (self.name, ", ".join([topping.name - for topping in self.toppings.all()])) + return "%s (%s)" % (self.name, ", ".join(topping.name + for topping in self.toppings.all())) and run:: @@ -1600,7 +1600,7 @@ found, ``get_or_create()`` will instantiate and save a new object, returning a tuple of the new object and ``True``. The new object will be created roughly according to this algorithm:: - params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) + params = {k: v for k, v in kwargs.items() if '__' not in k} params.update(defaults) obj = self.model(**params) obj.save() diff --git a/tests/cache/tests.py b/tests/cache/tests.py index bdbde46336d..9762620afce 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -219,7 +219,7 @@ def caches_setting_for_tests(base=None, **params): # This results in the following search order: # params -> _caches_setting_base -> base base = base or {} - setting = dict((k, base.copy()) for k in _caches_setting_base.keys()) + setting = {k: base.copy() for k in _caches_setting_base.keys()} for key, cache_params in setting.items(): cache_params.update(_caches_setting_base[key]) cache_params.update(params) diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py index de195f4d393..2b00192e2e6 100644 --- a/tests/file_uploads/views.py +++ b/tests/file_uploads/views.py @@ -92,7 +92,7 @@ def file_upload_echo(request): """ Simple view to echo back info about uploaded files for tests. """ - r = dict((k, f.name) for k, f in request.FILES.items()) + r = {k: f.name for k, f in request.FILES.items()} return HttpResponse(json.dumps(r)) @@ -100,7 +100,7 @@ def file_upload_echo_content(request): """ Simple view to echo back the content of uploaded files for tests. """ - r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items()) + r = {k: f.read().decode('utf-8') for k, f in request.FILES.items()} return HttpResponse(json.dumps(r)) @@ -153,9 +153,9 @@ def file_upload_content_type_extra(request): """ params = {} for file_name, uploadedfile in request.FILES.items(): - params[file_name] = dict([ - (k, smart_str(v)) for k, v in uploadedfile.content_type_extra.items() - ]) + params[file_name] = { + k: smart_str(v) for k, v in uploadedfile.content_type_extra.items() + } return HttpResponse(json.dumps(params)) diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py index 761d337e498..8982efed51c 100644 --- a/tests/model_formsets_regress/tests.py +++ b/tests/model_formsets_regress/tests.py @@ -438,10 +438,10 @@ class FormfieldShouldDeleteFormTests(TestCase): # pass standard data dict & see none updated data = dict(self.data) data['form-INITIAL_FORMS'] = 4 - data.update(dict( - ('form-%d-id' % i, user.pk) + data.update({ + 'form-%d-id' % i: user.pk for i, user in enumerate(User.objects.all()) - )) + }) formset = self.NormalFormset(data, queryset=User.objects.all()) self.assertTrue(formset.is_valid()) self.assertEqual(len(formset.save()), 0) @@ -455,10 +455,10 @@ class FormfieldShouldDeleteFormTests(TestCase): # create data dict with all fields marked for deletion data = dict(self.data) data['form-INITIAL_FORMS'] = 4 - data.update(dict( - ('form-%d-id' % i, user.pk) + data.update({ + 'form-%d-id' % i: user.pk for i, user in enumerate(User.objects.all()) - )) + }) data.update(self.delete_all_ids) formset = self.NormalFormset(data, queryset=User.objects.all()) self.assertTrue(formset.is_valid()) @@ -474,10 +474,10 @@ class FormfieldShouldDeleteFormTests(TestCase): # create data dict with all fields marked for deletion data = dict(self.data) data['form-INITIAL_FORMS'] = 4 - data.update(dict( - ('form-%d-id' % i, user.pk) + data.update({ + 'form-%d-id' % i: user.pk for i, user in enumerate(User.objects.all()) - )) + }) data.update(self.delete_all_ids) formset = self.DeleteFormset(data, queryset=User.objects.all()) diff --git a/tests/model_meta/test.py b/tests/model_meta/test.py index cbc348eae35..9901631a700 100644 --- a/tests/model_meta/test.py +++ b/tests/model_meta/test.py @@ -497,10 +497,10 @@ TEST_RESULTS = { class OptionsBaseTests(test.TestCase): def _map_rq_names(self, res): - return tuple([(o.field.related_query_name(), m) for o, m in res]) + return tuple((o.field.related_query_name(), m) for o, m in res) def _map_names(self, res): - return tuple([(f.name, m) for f, m in res]) + return tuple((f.name, m) for f, m in res) class DataTests(OptionsBaseTests): diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index 5fe37d59664..d8d5c19f8e7 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -653,9 +653,9 @@ class DefaultManagerTests(TestCase): # the default manager on teachers to immediately get all the related # qualifications, since this will do one query per teacher. qs = Department.objects.prefetch_related('teachers') - depts = "".join(["%s department: %s\n" % - (dept.name, ", ".join(six.text_type(t) for t in dept.teachers.all())) - for dept in qs]) + depts = "".join("%s department: %s\n" % + (dept.name, ", ".join(six.text_type(t) for t in dept.teachers.all())) + for dept in qs) self.assertEqual(depts, "English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n" @@ -990,9 +990,9 @@ class MultiDbTests(TestCase): # Forward qs1 = B.prefetch_related('authors') with self.assertNumQueries(2, using='other'): - books = "".join(["%s (%s)\n" % - (book.title, ", ".join(a.name for a in book.authors.all())) - for book in qs1]) + books = "".join("%s (%s)\n" % + (book.title, ", ".join(a.name for a in book.authors.all())) + for book in qs1) self.assertEqual(books, "Poems (Charlotte, Anne, Emily)\n" "Jane Eyre (Charlotte)\n" @@ -1002,9 +1002,9 @@ class MultiDbTests(TestCase): # Reverse qs2 = A.prefetch_related('books') with self.assertNumQueries(2, using='other'): - authors = "".join(["%s: %s\n" % - (author.name, ", ".join(b.title for b in author.books.all())) - for author in qs2]) + authors = "".join("%s: %s\n" % + (author.name, ", ".join(b.title for b in author.books.all())) + for author in qs2) self.assertEqual(authors, "Charlotte: Poems, Jane Eyre\n" "Anne: Poems\n" diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 730af87abf3..4e11c2696a4 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -64,13 +64,13 @@ class SchemaTests(TransactionTestCase): def column_classes(self, model): with connection.cursor() as cursor: - columns = dict( - (d[0], (connection.introspection.get_field_type(d[1], d), d)) + columns = { + d[0]: (connection.introspection.get_field_type(d[1], d), d) for d in connection.introspection.get_table_description( cursor, model._meta.db_table, ) - ) + } # SQLite has a different format for field_type for name, (type, desc) in columns.items(): if isinstance(type, tuple):