Skip to content

Commit

Permalink
Fixed #23968 -- Replaced list comprehension with generators and dict …
Browse files Browse the repository at this point in the history
…comprehension
  • Loading branch information
jdufresne authored and timgraham committed Dec 8, 2014
1 parent b327a61 commit 4468c08
Show file tree
Hide file tree
Showing 65 changed files with 169 additions and 169 deletions.
4 changes: 2 additions & 2 deletions django/contrib/admin/filters.py
Expand Up @@ -293,8 +293,8 @@ def choices(self, cl):
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
Expand Down
12 changes: 6 additions & 6 deletions django/contrib/contenttypes/management.py
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/gdal/field.py
Expand Up @@ -216,4 +216,4 @@ class OFTWideStringList(Field):
10: OFTTime,
11: OFTDateTime,
}
ROGRFieldTypes = dict((cls, num) for num, cls in OGRFieldTypes.items())
ROGRFieldTypes = {cls: num for num, cls in OGRFieldTypes.items()}
2 changes: 1 addition & 1 deletion django/contrib/gis/gdal/geomtype.py
Expand Up @@ -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."
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/gdal/libgdal.py
Expand Up @@ -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'])
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/geoip/base.py
Expand Up @@ -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 = ''
Expand Down
6 changes: 3 additions & 3 deletions django/contrib/gis/geoip/libgeoip.py
Expand Up @@ -4,9 +4,9 @@
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
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/geoip/prototypes.py
Expand Up @@ -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']]
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/geometry/test_data.py
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/gis/geos/libgeos.py
Expand Up @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions django/contrib/gis/management/commands/ogrinspect.py
Expand Up @@ -90,8 +90,8 @@ def handle(self, *args, **options):
# 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']:
Expand All @@ -104,7 +104,7 @@ def handle(self, *args, **options):
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'," % (
Expand Down
8 changes: 4 additions & 4 deletions django/contrib/gis/measure.py
Expand Up @@ -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__):
Expand All @@ -313,9 +313,9 @@ def __mul__(self, other):
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):
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/tests/geo3d/tests.py
Expand Up @@ -38,7 +38,7 @@
)

# 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
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/utils/layermapping.py
Expand Up @@ -329,7 +329,7 @@ def unique_kwargs(self, kwargs):
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):
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/messages/storage/cookie.py
Expand Up @@ -41,8 +41,8 @@ def process_messages(self, obj):
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):
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/messages/tests/base.py
Expand Up @@ -207,7 +207,7 @@ def test_multiple_posts(self):
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)
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/postgres/forms/array.py
Expand Up @@ -26,7 +26,7 @@ def __init__(self, base_field, delimiter=',', max_length=None, min_length=None,

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):
Expand Down
18 changes: 9 additions & 9 deletions django/core/management/__init__.py
Expand Up @@ -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
Expand Down Expand Up @@ -237,25 +237,25 @@ def autocomplete(self):
# '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]
Expand Down
2 changes: 1 addition & 1 deletion django/core/management/base.py
Expand Up @@ -58,7 +58,7 @@ def __init__(self, cmd, **kwargs):
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)

Expand Down
2 changes: 1 addition & 1 deletion django/core/management/commands/compilemessages.py
Expand Up @@ -60,7 +60,7 @@ def handle(self, **options):
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)))
Expand Down
2 changes: 1 addition & 1 deletion django/core/management/commands/diffsettings.py
Expand Up @@ -3,7 +3,7 @@

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):
Expand Down
4 changes: 2 additions & 2 deletions django/core/management/commands/inspectdb.py
Expand Up @@ -134,9 +134,9 @@ def handle_inspection(self, options):
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)
Expand Down
14 changes: 7 additions & 7 deletions django/core/management/commands/makemigrations.py
Expand Up @@ -66,10 +66,10 @@ def handle(self, *app_labels, **options):

# 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(
Expand Down Expand Up @@ -103,10 +103,10 @@ def handle(self, *app_labels, **options):
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,
Expand Down Expand Up @@ -224,7 +224,7 @@ def handle_merge(self, loader, conflicts):
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, ), {
Expand Down
4 changes: 2 additions & 2 deletions django/core/management/sql.py
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion django/core/urlresolvers.py
Expand Up @@ -428,7 +428,7 @@ def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
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()
Expand Down
6 changes: 3 additions & 3 deletions django/db/backends/__init__.py
Expand Up @@ -918,7 +918,7 @@ def last_executed_query(self, cursor, sql, params):
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)

Expand Down Expand Up @@ -1302,8 +1302,8 @@ def table_names(self, cursor=None, include_views=False):
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)
Expand Down
4 changes: 2 additions & 2 deletions django/db/backends/mysql/introspection.py
Expand Up @@ -62,7 +62,7 @@ def get_table_description(self, cursor, table_name):
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
Expand All @@ -85,7 +85,7 @@ def _name_to_index(self, cursor, table_name):
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):
"""
Expand Down

0 comments on commit 4468c08

Please sign in to comment.