1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

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):
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

View File

@ -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)

View File

@ -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()}

View File

@ -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."

View File

@ -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'])

View File

@ -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 = ''

View File

@ -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

View File

@ -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']]

View File

@ -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):

View File

@ -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()

View File

@ -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'," % (

View File

@ -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):

View File

@ -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

View File

@ -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):

View File

@ -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):

View File

@ -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)

View File

@ -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):

View File

@ -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]

View File

@ -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)

View File

@ -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)))

View File

@ -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):

View File

@ -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)

View File

@ -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, ), {

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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):
"""

View File

@ -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

View File

@ -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):
"""

View File

@ -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])))

View File

@ -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,

View File

@ -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):

View File

@ -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):
"""

View File

@ -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):

View File

@ -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 ""

View File

@ -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(

View File

@ -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):
"""

View File

@ -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

View File

@ -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):
"""

View File

@ -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):

View File

@ -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):

View File

@ -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)

View File

@ -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:

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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),

View File

@ -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

View File

@ -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):

View File

@ -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)

View File

@ -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:

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
# 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)

View File

@ -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))

View File

@ -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'}

View File

@ -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)

View File

@ -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:

View File

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

View File

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

View File

@ -882,8 +882,8 @@ For example, suppose you have these models::
toppings = models.ManyToManyField(Topping)
def __str__(self): # __unicode__ on Python 2
return "%s (%s)" % (self.name, ", ".join([topping.name
for topping in self.toppings.all()]))
return "%s (%s)" % (self.name, ", ".join(topping.name
for topping in self.toppings.all()))
and run::
@ -1600,7 +1600,7 @@ found, ``get_or_create()`` will instantiate and save a new object, returning a
tuple of the new object and ``True``. The new object will be created roughly
according to this algorithm::
params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
params = {k: v for k, v in kwargs.items() if '__' not in k}
params.update(defaults)
obj = self.model(**params)
obj.save()

View File

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

View File

@ -92,7 +92,7 @@ def file_upload_echo(request):
"""
Simple view to echo back info about uploaded files for tests.
"""
r = dict((k, f.name) for k, f in request.FILES.items())
r = {k: f.name for k, f in request.FILES.items()}
return HttpResponse(json.dumps(r))
@ -100,7 +100,7 @@ def file_upload_echo_content(request):
"""
Simple view to echo back the content of uploaded files for tests.
"""
r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items())
r = {k: f.read().decode('utf-8') for k, f in request.FILES.items()}
return HttpResponse(json.dumps(r))
@ -153,9 +153,9 @@ def file_upload_content_type_extra(request):
"""
params = {}
for file_name, uploadedfile in request.FILES.items():
params[file_name] = dict([
(k, smart_str(v)) for k, v in uploadedfile.content_type_extra.items()
])
params[file_name] = {
k: smart_str(v) for k, v in uploadedfile.content_type_extra.items()
}
return HttpResponse(json.dumps(params))

View File

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

View File

@ -497,10 +497,10 @@ TEST_RESULTS = {
class OptionsBaseTests(test.TestCase):
def _map_rq_names(self, res):
return tuple([(o.field.related_query_name(), m) for o, m in res])
return tuple((o.field.related_query_name(), m) for o, m in res)
def _map_names(self, res):
return tuple([(f.name, m) for f, m in res])
return tuple((f.name, m) for f, m in res)
class DataTests(OptionsBaseTests):

View File

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

View File

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