diff options
author | Jon Dufresne <jon.dufresne@gmail.com> | 2014-12-06 13:00:09 -0800 |
---|---|---|
committer | Tim Graham <timograham@gmail.com> | 2014-12-08 07:58:23 -0500 |
commit | 4468c08d70b5b722f3ebd4872909e56580ec7d68 (patch) | |
tree | 3da12d757bc9b586df4ba39da20b8793abcae76e /django | |
parent | b327a614eb7d885441c6a2575e10b70ac1352aae (diff) | |
download | django-4468c08d70b5b722f3ebd4872909e56580ec7d68.tar.gz |
Fixed #23968 -- Replaced list comprehension with generators and dict comprehension
Diffstat (limited to 'django')
56 files changed, 134 insertions, 134 deletions
diff --git a/django/contrib/admin/filters.py b/django/contrib/admin/filters.py index 1bdd637224..380d80d9a3 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 6da7c49ef5..6255f0ca37 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 dd60f3b953..f9bc1f7a55 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 1b5e079ef8..dc1f0480a3 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 7bcf93f518..65e58a3a33 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 08125e3615..9409019d94 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 73aa5fc9bf..cc4d92c7d0 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 8ddcb9d974..22c17f006f 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 3ad2f4aaea..d6a8bf8263 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 e503bbd3e6..207fa780a4 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 01930ff047..2e53eda6ad 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 456f1c7277..90b316bb60 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 47c141a2ac..740f0d5692 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 49a5f5f274..5031aadab8 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 02f13597dc..71eee0cdfa 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 9c8745784b..13b6fa0a3a 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 620c7c7b6e..0bd4ee4916 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 047e822e1a..55a88df178 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 5fe50bd71a..68bcb188e5 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 26ceb19261..dbadac0c7d 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 ac724fca3f..9729131b3f 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 32ee23581d..bc8d3be2f5 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 bc78ff5f84..8cce2fae76 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 275711a385..955d8391b3 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 62e3949df8..d7383a0422 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 dc4205e856..fcdb742f85 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 e60d12768a..d11b0bee47 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 aa97022931..8f025ef41e 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 37ed7e1f00..a16a021867 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 aa9ab85a4d..4ff155f572 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 40efa822b1..0ac2f25e04 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 4f3dfe9846..eab34454a2 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 5d62e2fb10..9cc428e162 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 39da247eca..b13e59c221 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 dec0eae33d..2e7afbd663 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 04189ad097..a3e4a1d9eb 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 6ab41dc21c..6e6d1abf3f 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 0fbe25cca7..bb1c52efd4 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 dadca18129..cad6372eea 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 950f9481a3..7ca8ddc2e2 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 42c62d5770..7ca4954358 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 0f085d57d5..ea32574c68 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 22e411270d..8a9099baa5 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 c6814983e7..405de785e8 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -562,8 +562,8 @@ class WithNode(Node): return "<WithNode>" 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 e758990c72..5bd0d27428 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 '<ExtendsNode: extends %s>' % 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 d9db91a413..0bfb4a9eff 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 62f7c5fb6c..a19970f02e 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 3d9a0d3526..dff9c4e25b 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 49fd9d9848..58108faa4b 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 cb45a2760b..422f55b9c5 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 e2c7a43c44..1644627967 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 39d548a9ce..40096741a7 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 1247849f31..3c03210c11 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 aa2cdc97c3..47bce5244c 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 eceaf20eba..a8d96893b0 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 55f9b231ea..09cc5c462e 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: |