Fixed #23968 -- Replaced list comprehension with generators and dict comprehension

This commit is contained in:
Jon Dufresne 2014-12-06 13:00:09 -08:00 committed by Tim Graham
parent b327a614eb
commit 4468c08d70
65 changed files with 169 additions and 169 deletions

View File

@ -293,8 +293,8 @@ FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter)
class DateFieldListFilter(FieldListFilter): class DateFieldListFilter(FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path): def __init__(self, field, request, params, model, model_admin, field_path):
self.field_generic = '%s__' % field_path self.field_generic = '%s__' % field_path
self.date_params = dict((k, v) for k, v in params.items() self.date_params = {k: v for k, v in params.items()
if k.startswith(self.field_generic)) if k.startswith(self.field_generic)}
now = timezone.now() now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time # When time zone support is enabled, convert "now" to the user's time

View File

@ -25,18 +25,18 @@ def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT
app_label = app_config.label app_label = app_config.label
app_models = dict( app_models = {
(model._meta.model_name, model) model._meta.model_name: model
for model in app_config.get_models()) for model in app_config.get_models()}
if not app_models: if not app_models:
return return
# Get all the content types # Get all the content types
content_types = dict( content_types = {
(ct.model, ct) ct.model: ct
for ct in ContentType.objects.using(using).filter(app_label=app_label) for ct in ContentType.objects.using(using).filter(app_label=app_label)
) }
to_remove = [ to_remove = [
ct ct
for (model_name, ct) in six.iteritems(content_types) for (model_name, ct) in six.iteritems(content_types)

View File

@ -216,4 +216,4 @@ OGRFieldTypes = {
10: OFTTime, 10: OFTTime,
11: OFTDateTime, 11: OFTDateTime,
} }
ROGRFieldTypes = dict((cls, num) for num, cls in OGRFieldTypes.items()) ROGRFieldTypes = {cls: num for num, cls in OGRFieldTypes.items()}

View File

@ -28,7 +28,7 @@ class OGRGeomType(object):
7 + wkb25bit: 'GeometryCollection25D', 7 + wkb25bit: 'GeometryCollection25D',
} }
# Reverse type dictionary, keyed by lower-case of the name. # 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): def __init__(self, type_input):
"Figures out the correct OGR Type based upon the input." "Figures out the correct OGR Type based upon the input."

View File

@ -91,7 +91,7 @@ def gdal_version_info():
m = version_regex.match(ver) m = version_regex.match(ver)
if not m: if not m:
raise OGRException('Could not parse GDAL version string "%s"' % ver) 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() _verinfo = gdal_version_info()
GDAL_MAJOR_VERSION = int(_verinfo['major']) GDAL_MAJOR_VERSION = int(_verinfo['major'])

View File

@ -48,7 +48,7 @@ class GeoIP(object):
GEOIP_CHECK_CACHE = 2 GEOIP_CHECK_CACHE = 2
GEOIP_INDEX_CACHE = 4 GEOIP_INDEX_CACHE = 4
GEOIP_MMAP_CACHE = 8 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. # Paths to the city & country binary databases.
_city_file = '' _city_file = ''

View File

@ -4,9 +4,9 @@ from ctypes.util import find_library
from django.conf import settings from django.conf import settings
# Creating the settings dictionary with any settings, if needed. # Creating the settings dictionary with any settings, if needed.
GEOIP_SETTINGS = dict((key, getattr(settings, key)) GEOIP_SETTINGS = {key: getattr(settings, key)
for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY') for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY')
if hasattr(settings, key)) if hasattr(settings, key)}
lib_path = GEOIP_SETTINGS.get('GEOIP_LIBRARY_PATH', None) lib_path = GEOIP_SETTINGS.get('GEOIP_LIBRARY_PATH', None)
# The shared library for the GeoIP C API. May be downloaded # The shared library for the GeoIP C API. May be downloaded

View File

@ -58,7 +58,7 @@ def check_record(result, func, cargs):
# Checking the pointer to the C structure, if valid pull out elements # Checking the pointer to the C structure, if valid pull out elements
# into a dictionary. # into a dictionary.
rec = result.contents 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. # Now converting the strings to unicode using the proper encoding.
encoding = geoip_encodings[record['charset']] encoding = geoip_encodings[record['charset']]

View File

@ -24,7 +24,7 @@ def tuplize(seq):
def strconvert(d): def strconvert(d):
"Converts all keys in dictionary to str type." "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): def get_ds_file(name, ext):

View File

@ -145,8 +145,8 @@ def geos_version_info():
m = version_regex.match(ver) m = version_regex.match(ver)
if not m: if not m:
raise GEOSException('Could not parse version info string "%s"' % ver) raise GEOSException('Could not parse version info string "%s"' % ver)
return dict((key, m.group(key)) for key in ( return {key: m.group(key) for key in (
'version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor')) 'version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor')}
# Version numbers and whether or not prepared geometry support is available. # Version numbers and whether or not prepared geometry support is available.
_verinfo = geos_version_info() _verinfo = geos_version_info()

View File

@ -90,8 +90,8 @@ class Command(BaseCommand):
# and options. # and options.
from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
# Filter options to params accepted by `_ogrinspect` # Filter options to params accepted by `_ogrinspect`
ogr_options = dict((k, v) for k, v in options.items() ogr_options = {k: v for k, v in options.items()
if k in inspect.getargspec(_ogrinspect).args and v is not None) if k in inspect.getargspec(_ogrinspect).args and v is not None}
output = [s for s in _ogrinspect(ds, model_name, **ogr_options)] output = [s for s in _ogrinspect(ds, model_name, **ogr_options)]
if options['mapping']: if options['mapping']:
@ -104,7 +104,7 @@ class Command(BaseCommand):
mapping_dict = mapping(ds, **kwargs) mapping_dict = mapping(ds, **kwargs)
# This extra legwork is so that the dictionary definition comes # This extra legwork is so that the dictionary definition comes
# out in the same order as the fields in the model definition. # 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, output.extend(['', '# Auto-generated `LayerMapping` dictionary for %s model' % model_name,
'%s_mapping = {' % model_name.lower()]) '%s_mapping = {' % model_name.lower()])
output.extend(" '%s' : '%s'," % ( output.extend(" '%s' : '%s'," % (

View File

@ -295,7 +295,7 @@ class Distance(MeasureBase):
'Yard (Indian)': 'indian_yd', 'Yard (Indian)': 'indian_yd',
'Yard (Sears)': 'sears_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): def __mul__(self, other):
if isinstance(other, self.__class__): if isinstance(other, self.__class__):
@ -313,9 +313,9 @@ class Distance(MeasureBase):
class Area(MeasureBase): class Area(MeasureBase):
STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT
# Getting the square units values and the alias dictionary. # 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()) UNITS = {'%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()) ALIAS = {k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()}
LALIAS = dict((k.lower(), v) for k, v in ALIAS.items()) LALIAS = {k.lower(): v for k, v in ALIAS.items()}
def __truediv__(self, other): def __truediv__(self, other):
if isinstance(other, NUMERIC_TYPES): if isinstance(other, NUMERIC_TYPES):

View File

@ -38,7 +38,7 @@ city_data = (
) )
# Reference mapping of city name to its altitude (Z value). # 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: # 3D freeway data derived from the National Elevation Dataset:
# http://seamless.usgs.gov/products/9arc.php # http://seamless.usgs.gov/products/9arc.php

View File

@ -329,7 +329,7 @@ class LayerMapping(object):
if isinstance(self.unique, six.string_types): if isinstance(self.unique, six.string_types):
return {self.unique: kwargs[self.unique]} return {self.unique: kwargs[self.unique]}
else: 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. #### #### Verification routines used in constructing model keyword arguments. ####
def verify_ogr_field(self, ogr_field, model_field): def verify_ogr_field(self, ogr_field, model_field):

View File

@ -41,8 +41,8 @@ class MessageDecoder(json.JSONDecoder):
return Message(*obj[2:]) return Message(*obj[2:])
return [self.process_messages(item) for item in obj] return [self.process_messages(item) for item in obj]
if isinstance(obj, dict): if isinstance(obj, dict):
return dict((key, self.process_messages(value)) return {key: self.process_messages(value)
for key, value in six.iteritems(obj)) for key, value in six.iteritems(obj)}
return obj return obj
def decode(self, s, **kwargs): def decode(self, s, **kwargs):

View File

@ -207,7 +207,7 @@ class BaseTests(object):
show_url = reverse('show_message') show_url = reverse('show_message')
messages = [] messages = []
for level in ('debug', 'info', 'success', 'warning', 'error'): 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,)) add_url = reverse('add_message', args=(level,))
self.client.post(add_url, data) self.client.post(add_url, data)
response = self.client.get(show_url) response = self.client.get(show_url)

View File

@ -26,7 +26,7 @@ class SimpleArrayField(forms.CharField):
def prepare_value(self, value): def prepare_value(self, value):
if isinstance(value, list): 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 return value
def to_python(self, value): def to_python(self, value):

View File

@ -103,9 +103,9 @@ def call_command(name, *args, **options):
parser = command.create_parser('', name) parser = command.create_parser('', name)
if command.use_argparse: if command.use_argparse:
# Use the `dest` option name from the parser option # Use the `dest` option name from the parser option
opt_mapping = dict((sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'), s_opt.dest) opt_mapping = {sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'): s_opt.dest
for s_opt in parser._actions if s_opt.option_strings) 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()) arg_options = {opt_mapping.get(key, key): value for key, value in options.items()}
defaults = parser.parse_args(args=args) defaults = parser.parse_args(args=args)
defaults = dict(defaults._get_kwargs(), **arg_options) defaults = dict(defaults._get_kwargs(), **arg_options)
# Move positional args out of options to mimic legacy optparse # Move positional args out of options to mimic legacy optparse
@ -237,25 +237,25 @@ class ManagementUtility(object):
# 'key=value' pairs # 'key=value' pairs
if cwords[0] == 'runfcgi': if cwords[0] == 'runfcgi':
from django.core.servers.fastcgi import FASTCGI_OPTIONS 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 # special case: add the names of installed apps to options
elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear', elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear',
'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'): 'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'):
try: try:
app_configs = apps.get_app_configs() app_configs = apps.get_app_configs()
# Get the last part of the dotted path as the app name. # 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: except ImportError:
# Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
# user will find out once they execute the command. # user will find out once they execute the command.
pass pass
parser = subcommand_cls.create_parser('', cwords[0]) parser = subcommand_cls.create_parser('', cwords[0])
if subcommand_cls.use_argparse: if subcommand_cls.use_argparse:
options += [(sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in options.extend((sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in
parser._actions if s_opt.option_strings] parser._actions if s_opt.option_strings)
else: else:
options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in options.extend((s_opt.get_opt_string(), s_opt.nargs) for s_opt in
parser.option_list] parser.option_list)
# filter out previously specified options from available options # filter out previously specified options from available options
prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] 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] options = [opt for opt in options if opt[0] not in prev_opts]

View File

@ -58,7 +58,7 @@ class CommandParser(ArgumentParser):
def parse_args(self, args=None, namespace=None): def parse_args(self, args=None, namespace=None):
# Catch missing argument for a better error message # Catch missing argument for a better error message
if (hasattr(self.cmd, 'missing_args_message') and 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) self.error(self.cmd.missing_args_message)
return super(CommandParser, self).parse_args(args, namespace) return super(CommandParser, self).parse_args(args, namespace)

View File

@ -60,7 +60,7 @@ class Command(BaseCommand):
basedirs = [os.path.join('conf', 'locale'), 'locale'] basedirs = [os.path.join('conf', 'locale'), 'locale']
if os.environ.get('DJANGO_SETTINGS_MODULE'): if os.environ.get('DJANGO_SETTINGS_MODULE'):
from django.conf import settings 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. # Gather existing directories.
basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs)))

View File

@ -3,7 +3,7 @@ from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')): def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Converts a module namespace to a Python dictionary.""" """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): class Command(BaseCommand):

View File

@ -134,9 +134,9 @@ class Command(BaseCommand):
if extra_params: if extra_params:
if not field_desc.endswith('('): if not field_desc.endswith('('):
field_desc += ', ' field_desc += ', '
field_desc += ', '.join([ field_desc += ', '.join(
'%s=%s' % (k, strip_prefix(repr(v))) '%s=%s' % (k, strip_prefix(repr(v)))
for k, v in extra_params.items()]) for k, v in extra_params.items())
field_desc += ')' field_desc += ')'
if comment_notes: if comment_notes:
field_desc += ' # ' + ' '.join(comment_notes) field_desc += ' # ' + ' '.join(comment_notes)

View File

@ -66,10 +66,10 @@ class Command(BaseCommand):
# If app_labels is specified, filter out conflicting migrations for unspecified apps # If app_labels is specified, filter out conflicting migrations for unspecified apps
if app_labels: if app_labels:
conflicts = dict( conflicts = {
(app_label, conflict) for app_label, conflict in iteritems(conflicts) app_label: conflict for app_label, conflict in iteritems(conflicts)
if app_label in app_labels if app_label in app_labels
) }
if conflicts and not self.merge: if conflicts and not self.merge:
name_str = "; ".join( name_str = "; ".join(
@ -103,10 +103,10 @@ class Command(BaseCommand):
if not app_labels: if not app_labels:
raise CommandError("You must supply at least one app label when using --empty.") 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 # Make a fake changes() result we can pass to arrange_for_graph
changes = dict( changes = {
(app, [Migration("custom", app)]) app: [Migration("custom", app)]
for app in app_labels for app in app_labels
) }
changes = autodetector.arrange_for_graph( changes = autodetector.arrange_for_graph(
changes=changes, changes=changes,
graph=loader.graph, graph=loader.graph,
@ -224,7 +224,7 @@ class Command(BaseCommand):
for migration in merge_migrations for migration in merge_migrations
] ]
try: 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: except ValueError:
biggest_number = 1 biggest_number = 1
subclass = type("Migration", (Migration, ), { subclass = type("Migration", (Migration, ), {

View File

@ -62,8 +62,8 @@ def sql_create(app_config, style, connection):
if not_installed_models: if not_installed_models:
alter_sql = [] alter_sql = []
for model in not_installed_models: for model in not_installed_models:
alter_sql.extend(['-- ' + sql for sql in alter_sql.extend('-- ' + sql for sql in
connection.creation.sql_for_pending_references(model, style, pending_references)]) connection.creation.sql_for_pending_references(model, style, pending_references))
if alter_sql: if alter_sql:
final_output.append('-- The following references should be added but depend on non-existent tables:') final_output.append('-- The following references should be added but depend on non-existent tables:')
final_output.extend(alter_sql) final_output.extend(alter_sql)

View File

@ -428,7 +428,7 @@ class RegexURLResolver(LocaleRegexProvider):
if args and kwargs: if args and kwargs:
raise ValueError("Don't mix *args and **kwargs in call to reverse()!") raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
text_args = [force_text(v) for v in args] 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: if not self._populated:
self._populate() self._populate()

View File

@ -918,7 +918,7 @@ class BaseDatabaseOperations(object):
elif params is None: elif params is None:
u_params = () u_params = ()
else: 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) return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params)
@ -1302,8 +1302,8 @@ class BaseDatabaseIntrospection(object):
in sorting order between databases. in sorting order between databases.
""" """
def get_names(cursor): def get_names(cursor):
return sorted([ti.name for ti in self.get_table_list(cursor) return sorted(ti.name for ti in self.get_table_list(cursor)
if include_views or ti.type == 't']) if include_views or ti.type == 't')
if cursor is None: if cursor is None:
with self.connection.cursor() as cursor: with self.connection.cursor() as cursor:
return get_names(cursor) return get_names(cursor)

View File

@ -62,7 +62,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, extra SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, extra
FROM information_schema.columns FROM information_schema.columns
WHERE table_name = %s AND table_schema = DATABASE()""", [table_name]) 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)) 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 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. Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based. 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): def get_relations(self, cursor, table_name):
""" """

View File

@ -886,7 +886,7 @@ class FormatStylePlaceholderCursor(object):
def _format_params(self, params): def _format_params(self, params):
try: 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: except AttributeError:
return tuple(OracleParam(p, self, True) for p in params) return tuple(OracleParam(p, self, True) for p in params)
@ -911,7 +911,7 @@ class FormatStylePlaceholderCursor(object):
def _param_generator(self, params): def _param_generator(self, params):
# Try dict handling; if that fails, treat as sequence # Try dict handling; if that fails, treat as sequence
if hasattr(params, 'items'): 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: else:
return [p.force_bytes for p in params] return [p.force_bytes for p in params]
@ -927,7 +927,7 @@ class FormatStylePlaceholderCursor(object):
query = convert_unicode(query, self.charset) query = convert_unicode(query, self.charset)
elif hasattr(params, 'keys'): elif hasattr(params, 'keys'):
# Handle params as dict # 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) query = convert_unicode(query % args, self.charset)
else: else:
# Handle params as sequence # Handle params as sequence

View File

@ -74,7 +74,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
Returns a dictionary of {field_name: field_index} for the given table. Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based. 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): def get_relations(self, cursor, table_name):
""" """

View File

@ -61,7 +61,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
SELECT column_name, is_nullable, column_default SELECT column_name, is_nullable, column_default
FROM information_schema.columns FROM information_schema.columns
WHERE table_name = %s""", [table_name]) 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)) cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
return [FieldInfo(*((force_text(line[0]),) + line[1:6] return [FieldInfo(*((force_text(line[0]),) + line[1:6]
+ (field_map[force_text(line[0])][0] == 'YES', field_map[force_text(line[0])][1]))) + (field_map[force_text(line[0])][0] == 'YES', field_map[force_text(line[0])][1])))

View File

@ -49,10 +49,10 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
Shortcut to transform a model from old_model into new_model Shortcut to transform a model from old_model into new_model
""" """
# Work out the new fields dict / mapping # 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, # Since mapping might mix column names and default values,
# its values must be already quoted. # 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 # This maps field names (not columns) for things like unique_together
rename_mapping = {} rename_mapping = {}
# If any of the new or altered fields is introducing a new PK, # If any of the new or altered fields is introducing a new PK,

View File

@ -63,10 +63,10 @@ class MigrationAutodetector(object):
return ( return (
path, path,
[self.deep_deconstruct(value) for value in args], [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() for key, value in kwargs.items()
), },
) )
def only_relation_agnostic_fields(self, fields): def only_relation_agnostic_fields(self, fields):

View File

@ -315,7 +315,7 @@ class MigrationLoader(object):
if app_label in seen_apps: if app_label in seen_apps:
conflicting_apps.add(app_label) conflicting_apps.add(app_label)
seen_apps.setdefault(app_label, set()).add(migration_name) 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): def project_state(self, nodes=None, at_end=True):
""" """

View File

@ -35,7 +35,7 @@ class ProjectState(object):
def clone(self): def clone(self):
"Returns an exact copy of this ProjectState" "Returns an exact copy of this ProjectState"
return 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, real_apps=self.real_apps,
) )
@ -271,10 +271,10 @@ class ModelState(object):
elif isinstance(value, set): elif isinstance(value, set):
return set(cls.force_text_recursive(x) for x in value) return set(cls.force_text_recursive(x) for x in value)
elif isinstance(value, dict): elif isinstance(value, dict):
return dict( return {
(cls.force_text_recursive(k), cls.force_text_recursive(v)) cls.force_text_recursive(k): cls.force_text_recursive(v)
for k, v in value.items() for k, v in value.items()
) }
return value return value
def construct_fields(self): def construct_fields(self):

View File

@ -141,7 +141,7 @@ class MigrationWriter(object):
imports.add("from django.conf import settings") imports.add("from django.conf import settings")
else: else:
# No need to output bytestrings for dependencies # 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]) dependencies.append(" %s," % self.serialize(dependency)[0])
items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else "" items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else ""

View File

@ -405,7 +405,7 @@ class SingleRelatedObjectDescriptor(object):
rel_obj_attr = attrgetter(self.related.field.attname) rel_obj_attr = attrgetter(self.related.field.attname)
instance_attr = lambda obj: obj._get_pk_val() 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} query = {'%s__in' % self.related.field.name: instances}
queryset = queryset.filter(**query) queryset = queryset.filter(**query)
@ -536,7 +536,7 @@ class ReverseSingleRelatedObjectDescriptor(object):
rel_obj_attr = self.field.get_foreign_related_value rel_obj_attr = self.field.get_foreign_related_value
instance_attr = self.field.get_local_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] related_field = self.field.foreign_related_fields[0]
# FIXME: This will need to be revisited when we introduce support for # FIXME: This will need to be revisited when we introduce support for
@ -570,9 +570,9 @@ class ReverseSingleRelatedObjectDescriptor(object):
if None in val: if None in val:
rel_obj = None rel_obj = None
else: else:
params = dict( params = {
(rh_field.attname, getattr(instance, lh_field.attname)) rh_field.attname: getattr(instance, lh_field.attname)
for lh_field, rh_field in self.field.related_fields) for lh_field, rh_field in self.field.related_fields}
qs = self.get_queryset(instance=instance) qs = self.get_queryset(instance=instance)
extra_filter = self.field.get_extra_descriptor_filter(instance) extra_filter = self.field.get_extra_descriptor_filter(instance)
if isinstance(extra_filter, dict): 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 rel_obj_attr = rel_field.get_local_related_value
instance_attr = rel_field.get_foreign_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} query = {'%s__in' % rel_field.name: instances}
queryset = queryset.filter(**query) queryset = queryset.filter(**query)
@ -927,9 +927,9 @@ def create_many_related_manager(superclass, rel):
join_table = self.through._meta.db_table join_table = self.through._meta.db_table
connection = connections[queryset.db] connection = connections[queryset.db]
qn = connection.ops.quote_name qn = connection.ops.quote_name
queryset = queryset.extra(select=dict( queryset = queryset.extra(select={
('_prefetch_related_val_%s' % f.attname, '_prefetch_related_val_%s' % f.attname:
'%s.%s' % (qn(join_table), qn(f.column))) for f in fk.local_related_fields)) '%s.%s' % (qn(join_table), qn(f.column)) for f in fk.local_related_fields})
return ( return (
queryset, queryset,
lambda result: tuple( lambda result: tuple(

View File

@ -491,7 +491,7 @@ class QuerySet(object):
for f in self.model._meta.fields: for f in self.model._meta.fields:
if f.attname in lookup: if f.attname in lookup:
lookup[f.name] = lookup.pop(f.attname) 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) params.update(defaults)
return lookup, params return lookup, params
@ -545,7 +545,7 @@ class QuerySet(object):
if not id_list: if not id_list:
return {} return {}
qs = self.filter(pk__in=id_list).order_by() 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): def delete(self):
""" """

View File

@ -205,7 +205,7 @@ def deferred_class_factory(model, attrs):
proxy = True proxy = True
app_label = model._meta.app_label 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["Meta"] = Meta
overrides["__module__"] = model.__module__ overrides["__module__"] = model.__module__
overrides["_deferred"] = True overrides["_deferred"] = True

View File

@ -377,7 +377,7 @@ class Query(object):
inner_query.select_related = False inner_query.select_related = False
inner_query.related_select_cols = [] 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' relabels[None] = 'subquery'
# Remove any aggregates marked for reduction from the subquery # Remove any aggregates marked for reduction from the subquery
# and move them to the outer AggregateQuery. # and move them to the outer AggregateQuery.
@ -390,10 +390,10 @@ class Query(object):
try: try:
outer_query.add_subquery(inner_query, using) outer_query.add_subquery(inner_query, using)
except EmptyResultSet: except EmptyResultSet:
return dict( return {
(alias, None) alias: None
for alias in outer_query.annotation_select for alias in outer_query.annotation_select
) }
else: else:
outer_query = self outer_query = self
self.select = [] self.select = []
@ -421,11 +421,11 @@ class Query(object):
converters[position] = ([], [annotation.convert_value], annotation.output_field) converters[position] = ([], [annotation.convert_value], annotation.output_field)
result = compiler.apply_converters(result, converters) result = compiler.apply_converters(result, converters)
return dict( return {
(alias, val) alias: val
for (alias, annotation), val for (alias, annotation), val
in zip(outer_query.annotation_select.items(), result) in zip(outer_query.annotation_select.items(), result)
) }
def get_count(self, using): def get_count(self, using):
""" """

View File

@ -1028,7 +1028,7 @@ class MultiValueField(Field):
def __deepcopy__(self, memo): def __deepcopy__(self, memo):
result = super(MultiValueField, self).__deepcopy__(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 return result
def validate(self, value): def validate(self, value):

View File

@ -567,7 +567,7 @@ class BaseModelFormSet(BaseFormSet):
def _existing_object(self, pk): def _existing_object(self, pk):
if not hasattr(self, '_object_dict'): 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) return self._object_dict.get(pk)
def _get_to_python(self, field): def _get_to_python(self, field):

View File

@ -458,8 +458,8 @@ class QueryDict(MultiValueDict):
encode = lambda k, v: urlencode({k: v}) encode = lambda k, v: urlencode({k: v})
for k, list_ in self.lists(): for k, list_ in self.lists():
k = force_bytes(k, self.encoding) k = force_bytes(k, self.encoding)
output.extend([encode(k, force_bytes(v, self.encoding)) output.extend(encode(k, force_bytes(v, self.encoding))
for v in list_]) for v in list_)
return '&'.join(output) return '&'.join(output)

View File

@ -1058,7 +1058,7 @@ class TagHelperNode(Node):
resolved_args = [var.resolve(context) for var in self.args] resolved_args = [var.resolve(context) for var in self.args]
if self.takes_context: if self.takes_context:
resolved_args = [context] + resolved_args 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 return resolved_args, resolved_kwargs
@ -1301,9 +1301,9 @@ def get_templatetags_modules():
Caches the result for faster access. Caches the result for faster access.
""" """
templatetags_modules_candidates = ['django.templatetags'] templatetags_modules_candidates = ['django.templatetags']
templatetags_modules_candidates += [ templatetags_modules_candidates.extend(
'%s.templatetags' % app_config.name '%s.templatetags' % app_config.name
for app_config in apps.get_app_configs()] for app_config in apps.get_app_configs())
templatetags_modules = [] templatetags_modules = []
for templatetag_module in templatetags_modules_candidates: for templatetag_module in templatetags_modules_candidates:

View File

@ -562,8 +562,8 @@ class WithNode(Node):
return "<WithNode>" return "<WithNode>"
def render(self, context): def render(self, context):
values = dict((key, val.resolve(context)) for key, val in values = {key: val.resolve(context) for key, val in
six.iteritems(self.extra_context)) six.iteritems(self.extra_context)}
with context.push(**values): with context.push(**values):
return self.nodelist.render(context) return self.nodelist.render(context)

View File

@ -86,7 +86,7 @@ class ExtendsNode(Node):
self.nodelist = nodelist self.nodelist = nodelist
self.parent_name = parent_name self.parent_name = parent_name
self.template_dirs = template_dirs 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): def __repr__(self):
return '<ExtendsNode: extends %s>' % self.parent_name.token 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. # The ExtendsNode has to be the first non-text node.
if not isinstance(node, TextNode): if not isinstance(node, TextNode):
if not isinstance(node, ExtendsNode): if not isinstance(node, ExtendsNode):
blocks = dict((n.name, n) for n in blocks = {n.name: n for n in
compiled_parent.nodelist.get_nodes_by_type(BlockNode)) compiled_parent.nodelist.get_nodes_by_type(BlockNode)}
block_context.add_blocks(blocks) block_context.add_blocks(blocks)
break break

View File

@ -158,7 +158,7 @@ class BlockTranslateNode(Node):
val = default_value % key if '%s' in default_value else default_value val = default_value % key if '%s' in default_value else default_value
return render_value_in_context(val, context) 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() context.pop()
try: try:
result = result % data result = result % data

View File

@ -172,19 +172,19 @@ def encode_multipart(boundary, data):
if is_file(item): if is_file(item):
lines.extend(encode_file(boundary, key, item)) lines.extend(encode_file(boundary, key, item))
else: else:
lines.extend([to_bytes(val) for val in [ lines.extend(to_bytes(val) for val in [
'--%s' % boundary, '--%s' % boundary,
'Content-Disposition: form-data; name="%s"' % key, 'Content-Disposition: form-data; name="%s"' % key,
'', '',
item item
]]) ])
else: else:
lines.extend([to_bytes(val) for val in [ lines.extend(to_bytes(val) for val in [
'--%s' % boundary, '--%s' % boundary,
'Content-Disposition: form-data; name="%s"' % key, 'Content-Disposition: form-data; name="%s"' % key,
'', '',
value value
]]) ])
lines.extend([ lines.extend([
to_bytes('--%s--' % boundary), to_bytes('--%s--' % boundary),

View File

@ -309,8 +309,8 @@ def compare_xml(want, got):
return _norm_whitespace_re.sub(' ', v) return _norm_whitespace_re.sub(' ', v)
def child_text(element): def child_text(element):
return ''.join([c.data for c in element.childNodes return ''.join(c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE]) if c.nodeType == Node.TEXT_NODE)
def children(element): def children(element):
return [c for c in element.childNodes return [c for c in element.childNodes

View File

@ -346,7 +346,7 @@ class MultiValueDict(dict):
def __getstate__(self): def __getstate__(self):
obj_dict = self.__dict__.copy() 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 return obj_dict
def __setstate__(self, obj_dict): def __setstate__(self, obj_dict):
@ -467,7 +467,7 @@ class MultiValueDict(dict):
""" """
Returns current object as a dict with singular values. 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): class ImmutableList(tuple):

View File

@ -36,7 +36,7 @@ def parse_date(value):
""" """
match = date_re.match(value) match = date_re.match(value)
if match: 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) return datetime.date(**kw)
@ -54,7 +54,7 @@ def parse_time(value):
kw = match.groupdict() kw = match.groupdict()
if kw['microsecond']: if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0') 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) return datetime.time(**kw)
@ -81,6 +81,6 @@ def parse_datetime(value):
if tzinfo[0] == '-': if tzinfo[0] == '-':
offset = -offset offset = -offset
tzinfo = get_fixed_timezone(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 kw['tzinfo'] = tzinfo
return datetime.datetime(**kw) return datetime.datetime(**kw)

View File

@ -264,7 +264,7 @@ class BaseConfigurator(object):
c = self.resolve(c) c = self.resolve(c)
props = config.pop('.', None) props = config.pop('.', None)
# Check for valid identifiers # 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) result = c(**kwargs)
if props: if props:
for name, value in props.items(): for name, value in props.items():
@ -502,7 +502,7 @@ class DictConfigurator(BaseConfigurator):
'address' in config: 'address' in config:
config['address'] = self.as_tuple(config['address']) config['address'] = self.as_tuple(config['address'])
factory = klass 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: try:
result = factory(**kwargs) result = factory(**kwargs)
except TypeError as te: except TypeError as te:

View File

@ -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 # working unicode method. Try to handle this without raising a
# further exception by individually forcing the exception args # further exception by individually forcing the exception args
# to unicode. # to unicode.
s = ' '.join([force_text(arg, encoding, strings_only, s = ' '.join(force_text(arg, encoding, strings_only, errors)
errors) for arg in s]) for arg in s)
return 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 # An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a # know how to print itself properly. We shouldn't raise a
# further exception. # further exception.
return b' '.join([force_bytes(arg, encoding, strings_only, return b' '.join(force_bytes(arg, encoding, strings_only, errors)
errors) for arg in s]) for arg in s)
return six.text_type(s).encode(encoding, errors) return six.text_type(s).encode(encoding, errors)
else: else:
return s.encode(encoding, errors) return s.encode(encoding, errors)

View File

@ -90,7 +90,7 @@ def format_html(format_string, *args, **kwargs):
of str.format or % interpolation to build up small HTML fragments. of str.format or % interpolation to build up small HTML fragments.
""" """
args_safe = map(conditional_escape, args) 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)) return mark_safe(format_string.format(*args_safe, **kwargs_safe))

View File

@ -5,8 +5,8 @@ termcolors.py
from django.utils import six from django.utils import six
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict((color_names[x], '3%s' % x) for x in range(8)) foreground = {color_names[x]: '3%s' % x for x in range(8)}
background = dict((color_names[x], '4%s' % x) for x in range(8)) background = {color_names[x]: '4%s' % x for x in range(8)}
RESET = '0' RESET = '0'
opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}

View File

@ -43,10 +43,10 @@ class Node(object):
def __str__(self): def __str__(self):
if self.negated: if self.negated:
return '(NOT (%s: %s))' % (self.connector, ', '.join([str(c) for c return '(NOT (%s: %s))' % (self.connector, ', '.join(str(c) for c
in self.children])) in self.children))
return '(%s: %s)' % (self.connector, ', '.join([str(c) for c in return '(%s: %s)' % (self.connector, ', '.join(str(c) for c in
self.children])) self.children))
def __repr__(self): def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self) return "<%s: %s>" % (self.__class__.__name__, self)

View File

@ -59,7 +59,7 @@ def cleanse_setting(key, value):
cleansed = CLEANSED_SUBSTITUTE cleansed = CLEANSED_SUBSTITUTE
else: else:
if isinstance(value, dict): 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: else:
cleansed = value cleansed = value
except TypeError: except TypeError:

View File

@ -53,7 +53,7 @@ def main(argv=None):
files = [] files = []
for root in argv[1:]: for root in argv[1:]:
for (dirpath, dirnames, filenames) in os.walk(root): 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.sort()
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')] files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
#print files #print files

View File

@ -145,8 +145,8 @@ def colorize(text='', opts=(), **kwargs):
print('this should not be red') print('this should not be red')
""" """
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) foreground = {color_names[x]: '3%s' % x for x in range(8)}
background = dict([(color_names[x], '4%s' % x) for x in range(8)]) background = {color_names[x]: '4%s' % x for x in range(8)}
RESET = '0' RESET = '0'
opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}

View File

@ -882,8 +882,8 @@ For example, suppose you have these models::
toppings = models.ManyToManyField(Topping) toppings = models.ManyToManyField(Topping)
def __str__(self): # __unicode__ on Python 2 def __str__(self): # __unicode__ on Python 2
return "%s (%s)" % (self.name, ", ".join([topping.name return "%s (%s)" % (self.name, ", ".join(topping.name
for topping in self.toppings.all()])) for topping in self.toppings.all()))
and run:: 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 tuple of the new object and ``True``. The new object will be created roughly
according to this algorithm:: 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) params.update(defaults)
obj = self.model(**params) obj = self.model(**params)
obj.save() obj.save()

View File

@ -219,7 +219,7 @@ def caches_setting_for_tests(base=None, **params):
# This results in the following search order: # This results in the following search order:
# params -> _caches_setting_base -> base # params -> _caches_setting_base -> base
base = base or {} 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(): for key, cache_params in setting.items():
cache_params.update(_caches_setting_base[key]) cache_params.update(_caches_setting_base[key])
cache_params.update(params) cache_params.update(params)

View File

@ -92,7 +92,7 @@ def file_upload_echo(request):
""" """
Simple view to echo back info about uploaded files for tests. 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)) 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. 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)) return HttpResponse(json.dumps(r))
@ -153,9 +153,9 @@ def file_upload_content_type_extra(request):
""" """
params = {} params = {}
for file_name, uploadedfile in request.FILES.items(): for file_name, uploadedfile in request.FILES.items():
params[file_name] = dict([ params[file_name] = {
(k, smart_str(v)) for k, v in uploadedfile.content_type_extra.items() k: smart_str(v) for k, v in uploadedfile.content_type_extra.items()
]) }
return HttpResponse(json.dumps(params)) return HttpResponse(json.dumps(params))

View File

@ -438,10 +438,10 @@ class FormfieldShouldDeleteFormTests(TestCase):
# pass standard data dict & see none updated # pass standard data dict & see none updated
data = dict(self.data) data = dict(self.data)
data['form-INITIAL_FORMS'] = 4 data['form-INITIAL_FORMS'] = 4
data.update(dict( data.update({
('form-%d-id' % i, user.pk) 'form-%d-id' % i: user.pk
for i, user in enumerate(User.objects.all()) for i, user in enumerate(User.objects.all())
)) })
formset = self.NormalFormset(data, queryset=User.objects.all()) formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(formset.is_valid()) self.assertTrue(formset.is_valid())
self.assertEqual(len(formset.save()), 0) self.assertEqual(len(formset.save()), 0)
@ -455,10 +455,10 @@ class FormfieldShouldDeleteFormTests(TestCase):
# create data dict with all fields marked for deletion # create data dict with all fields marked for deletion
data = dict(self.data) data = dict(self.data)
data['form-INITIAL_FORMS'] = 4 data['form-INITIAL_FORMS'] = 4
data.update(dict( data.update({
('form-%d-id' % i, user.pk) 'form-%d-id' % i: user.pk
for i, user in enumerate(User.objects.all()) for i, user in enumerate(User.objects.all())
)) })
data.update(self.delete_all_ids) data.update(self.delete_all_ids)
formset = self.NormalFormset(data, queryset=User.objects.all()) formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(formset.is_valid()) self.assertTrue(formset.is_valid())
@ -474,10 +474,10 @@ class FormfieldShouldDeleteFormTests(TestCase):
# create data dict with all fields marked for deletion # create data dict with all fields marked for deletion
data = dict(self.data) data = dict(self.data)
data['form-INITIAL_FORMS'] = 4 data['form-INITIAL_FORMS'] = 4
data.update(dict( data.update({
('form-%d-id' % i, user.pk) 'form-%d-id' % i: user.pk
for i, user in enumerate(User.objects.all()) for i, user in enumerate(User.objects.all())
)) })
data.update(self.delete_all_ids) data.update(self.delete_all_ids)
formset = self.DeleteFormset(data, queryset=User.objects.all()) formset = self.DeleteFormset(data, queryset=User.objects.all())

View File

@ -497,10 +497,10 @@ TEST_RESULTS = {
class OptionsBaseTests(test.TestCase): class OptionsBaseTests(test.TestCase):
def _map_rq_names(self, res): 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): 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): class DataTests(OptionsBaseTests):

View File

@ -653,9 +653,9 @@ class DefaultManagerTests(TestCase):
# the default manager on teachers to immediately get all the related # the default manager on teachers to immediately get all the related
# qualifications, since this will do one query per teacher. # qualifications, since this will do one query per teacher.
qs = Department.objects.prefetch_related('teachers') qs = Department.objects.prefetch_related('teachers')
depts = "".join(["%s department: %s\n" % depts = "".join("%s department: %s\n" %
(dept.name, ", ".join(six.text_type(t) for t in dept.teachers.all())) (dept.name, ", ".join(six.text_type(t) for t in dept.teachers.all()))
for dept in qs]) for dept in qs)
self.assertEqual(depts, self.assertEqual(depts,
"English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n" "English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n"
@ -990,9 +990,9 @@ class MultiDbTests(TestCase):
# Forward # Forward
qs1 = B.prefetch_related('authors') qs1 = B.prefetch_related('authors')
with self.assertNumQueries(2, using='other'): with self.assertNumQueries(2, using='other'):
books = "".join(["%s (%s)\n" % books = "".join("%s (%s)\n" %
(book.title, ", ".join(a.name for a in book.authors.all())) (book.title, ", ".join(a.name for a in book.authors.all()))
for book in qs1]) for book in qs1)
self.assertEqual(books, self.assertEqual(books,
"Poems (Charlotte, Anne, Emily)\n" "Poems (Charlotte, Anne, Emily)\n"
"Jane Eyre (Charlotte)\n" "Jane Eyre (Charlotte)\n"
@ -1002,9 +1002,9 @@ class MultiDbTests(TestCase):
# Reverse # Reverse
qs2 = A.prefetch_related('books') qs2 = A.prefetch_related('books')
with self.assertNumQueries(2, using='other'): with self.assertNumQueries(2, using='other'):
authors = "".join(["%s: %s\n" % authors = "".join("%s: %s\n" %
(author.name, ", ".join(b.title for b in author.books.all())) (author.name, ", ".join(b.title for b in author.books.all()))
for author in qs2]) for author in qs2)
self.assertEqual(authors, self.assertEqual(authors,
"Charlotte: Poems, Jane Eyre\n" "Charlotte: Poems, Jane Eyre\n"
"Anne: Poems\n" "Anne: Poems\n"

View File

@ -64,13 +64,13 @@ class SchemaTests(TransactionTestCase):
def column_classes(self, model): def column_classes(self, model):
with connection.cursor() as cursor: with connection.cursor() as cursor:
columns = dict( columns = {
(d[0], (connection.introspection.get_field_type(d[1], d), d)) d[0]: (connection.introspection.get_field_type(d[1], d), d)
for d in connection.introspection.get_table_description( for d in connection.introspection.get_table_description(
cursor, cursor,
model._meta.db_table, model._meta.db_table,
) )
) }
# SQLite has a different format for field_type # SQLite has a different format for field_type
for name, (type, desc) in columns.items(): for name, (type, desc) in columns.items():
if isinstance(type, tuple): if isinstance(type, tuple):