Skip to content

Commit 2c69824

Browse files
jdufresnetimgraham
authored andcommitted
Refs #23968 -- Removed unnecessary lists, generators, and tuple calls.
1 parent edee5a8 commit 2c69824

File tree

63 files changed

+145
-150
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+145
-150
lines changed

django/apps/registry.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ def set_available_apps(self, available):
300300
This method is safe in the sense that it doesn't trigger any imports.
301301
"""
302302
available = set(available)
303-
installed = set(app_config.name for app_config in self.get_app_configs())
303+
installed = {app_config.name for app_config in self.get_app_configs()}
304304
if not available.issubset(installed):
305305
raise ValueError(
306306
"Available apps isn't a subset of installed apps, extra apps: %s"

django/contrib/admin/templatetags/admin_urls.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def add_preserved_filters(context, url, popup=False, to_field=None):
2525

2626
parsed_url = list(urlparse(url))
2727
parsed_qs = dict(parse_qsl(parsed_url[4]))
28-
merged_qs = dict()
28+
merged_qs = {}
2929

3030
if opts and preserved_filters:
3131
preserved_filters = dict(parse_qsl(preserved_filters))

django/contrib/auth/backends.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def _get_permissions(self, user_obj, obj, from_name):
5454
else:
5555
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
5656
perms = perms.values_list('content_type__app_label', 'codename').order_by()
57-
setattr(user_obj, perm_cache_name, set("%s.%s" % (ct, name) for ct, name in perms))
57+
setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms})
5858
return getattr(user_obj, perm_cache_name)
5959

6060
def get_user_permissions(self, user_obj, obj=None):

django/contrib/auth/management/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_
5050

5151
# This will hold the permissions we're looking for as
5252
# (content_type, (codename, name))
53-
searched_perms = list()
53+
searched_perms = []
5454
# The codenames and ctypes that should exist.
5555
ctypes = set()
5656
for klass in app_config.get_models():

django/contrib/contenttypes/fields.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,7 @@ def get_prefetch_queryset(self, instances, queryset=None):
529529

530530
query = {
531531
'%s__pk' % self.content_type_field_name: self.content_type.id,
532-
'%s__in' % self.object_id_field_name: set(obj._get_pk_val() for obj in instances)
532+
'%s__in' % self.object_id_field_name: {obj._get_pk_val() for obj in instances}
533533
}
534534

535535
# We (possibly) need to convert object IDs to the type of the

django/contrib/flatpages/templatetags/flatpages.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def get_flatpages(parser, token):
7272
bits = token.split_contents()
7373
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
7474
"['url_starts_with'] [for user] as context_name" %
75-
dict(tag_name=bits[0]))
75+
{'tag_name': bits[0]})
7676
# Must have at 3-6 bits in the tag
7777
if len(bits) >= 3 and len(bits) <= 6:
7878

django/core/cache/backends/memcached.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def __init__(self, server, params):
159159
@property
160160
def _cache(self):
161161
if getattr(self, '_client', None) is None:
162-
client_kwargs = dict(pickleProtocol=pickle.HIGHEST_PROTOCOL)
162+
client_kwargs = {'pickleProtocol': pickle.HIGHEST_PROTOCOL}
163163
client_kwargs.update(self._options)
164164
self._client = self._lib.Client(self._servers, **client_kwargs)
165165
return self._client

django/core/management/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ def check_migrations(self):
428428

429429
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
430430
if plan:
431-
apps_waiting_migration = sorted(set(migration.app_label for migration, backwards in plan))
431+
apps_waiting_migration = sorted({migration.app_label for migration, backwards in plan})
432432
self.stdout.write(
433433
self.style.NOTICE(
434434
"\nYou have %(unpplied_migration_count)s unapplied migration(s). "

django/core/management/commands/loaddata.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ def find_fixtures(self, fixture_label):
235235
'.'.join(ext for ext in combo if ext)
236236
for combo in product(databases, ser_fmts, cmp_fmts)
237237
)
238-
targets = set('.'.join((fixture_name, suffix)) for suffix in suffixes)
238+
targets = {'.'.join((fixture_name, suffix)) for suffix in suffixes}
239239

240240
fixture_files = []
241241
for fixture_dir in fixture_dirs:

django/core/management/commands/makemigrations.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def handle(self, *app_labels, **options):
7878
loader = MigrationLoader(None, ignore_no_migrations=True)
7979

8080
# Raise an error if any migrations are applied before their dependencies.
81-
consistency_check_labels = set(config.label for config in apps.get_app_configs())
81+
consistency_check_labels = {config.label for config in apps.get_app_configs()}
8282
# Non-default databases are only checked if database routers used.
8383
aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS]
8484
for alias in sorted(aliases_to_check):

django/core/management/commands/migrate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def handle(self, *args, **options):
143143
if target_app_labels_only:
144144
self.stdout.write(
145145
self.style.MIGRATE_LABEL(" Apply all migrations: ") +
146-
(", ".join(sorted(set(a for a, n in targets))) or "(none)")
146+
(", ".join(sorted({a for a, n in targets})) or "(none)")
147147
)
148148
else:
149149
if targets[0][1] is None:

django/db/backends/base/schema.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,8 @@ def alter_unique_together(self, model, old_unique_together, new_unique_together)
324324
unique_togethers must be doubly-nested, not the single-nested
325325
["foo", "bar"] format.
326326
"""
327-
olds = set(tuple(fields) for fields in old_unique_together)
328-
news = set(tuple(fields) for fields in new_unique_together)
327+
olds = {tuple(fields) for fields in old_unique_together}
328+
news = {tuple(fields) for fields in new_unique_together}
329329
# Deleted uniques
330330
for fields in olds.difference(news):
331331
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
@@ -340,8 +340,8 @@ def alter_index_together(self, model, old_index_together, new_index_together):
340340
index_togethers must be doubly-nested, not the single-nested
341341
["foo", "bar"] format.
342342
"""
343-
olds = set(tuple(fields) for fields in old_index_together)
344-
news = set(tuple(fields) for fields in new_index_together)
343+
olds = {tuple(fields) for fields in old_index_together}
344+
news = {tuple(fields) for fields in new_index_together}
345345
# Deleted indexes
346346
for fields in olds.difference(news):
347347
self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)

django/db/backends/sqlite3/schema.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def is_self_referential(f):
169169
'indexes': indexes,
170170
'apps': apps,
171171
}
172-
meta = type("Meta", tuple(), meta_contents)
172+
meta = type("Meta", (), meta_contents)
173173
body['Meta'] = meta
174174
body['__module__'] = model.__module__
175175

django/db/migrations/autodetector.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -1065,14 +1065,14 @@ def generate_altered_options(self):
10651065
old_model_name = self.renamed_models.get((app_label, model_name), model_name)
10661066
old_model_state = self.from_state.models[app_label, old_model_name]
10671067
new_model_state = self.to_state.models[app_label, model_name]
1068-
old_options = dict(
1069-
option for option in old_model_state.options.items()
1070-
if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
1071-
)
1072-
new_options = dict(
1073-
option for option in new_model_state.options.items()
1074-
if option[0] in AlterModelOptions.ALTER_OPTION_KEYS
1075-
)
1068+
old_options = {
1069+
key: value for key, value in old_model_state.options.items()
1070+
if key in AlterModelOptions.ALTER_OPTION_KEYS
1071+
}
1072+
new_options = {
1073+
key: value for key, value in new_model_state.options.items()
1074+
if key in AlterModelOptions.ALTER_OPTION_KEYS
1075+
}
10761076
if old_options != new_options:
10771077
self.add_operation(
10781078
app_label,

django/db/migrations/operations/models.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ class AlterUniqueTogether(FieldRelatedOptionOperation):
496496

497497
def __init__(self, name, unique_together):
498498
unique_together = normalize_together(unique_together)
499-
self.unique_together = set(tuple(cons) for cons in unique_together)
499+
self.unique_together = {tuple(cons) for cons in unique_together}
500500
super().__init__(name)
501501

502502
def deconstruct(self):
@@ -550,7 +550,7 @@ class AlterIndexTogether(FieldRelatedOptionOperation):
550550

551551
def __init__(self, name, index_together):
552552
index_together = normalize_together(index_together)
553-
self.index_together = set(tuple(cons) for cons in index_together)
553+
self.index_together = {tuple(cons) for cons in index_together}
554554
super().__init__(name)
555555

556556
def deconstruct(self):

django/db/migrations/recorder.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def ensure_schema(self):
5555
def applied_migrations(self):
5656
"""Return a set of (app, name) of applied migrations."""
5757
self.ensure_schema()
58-
return set(tuple(x) for x in self.migration_qs.values_list("app", "name"))
58+
return {tuple(x) for x in self.migration_qs.values_list("app", "name")}
5959

6060
def record_applied(self, app, name):
6161
"""Record that a migration was applied."""

django/db/migrations/state.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ def render(self, apps):
559559
# First, make a Meta object
560560
meta_contents = {'app_label': self.app_label, "apps": apps}
561561
meta_contents.update(self.options)
562-
meta = type("Meta", tuple(), meta_contents)
562+
meta = type("Meta", (), meta_contents)
563563
# Then, work out our bases
564564
try:
565565
bases = tuple(

django/db/models/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1294,7 +1294,7 @@ def _check_m2m_through_same_relationship(cls):
12941294
@classmethod
12951295
def _check_id_field(cls):
12961296
"""Check if `id` field is a primary key."""
1297-
fields = list(f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk)
1297+
fields = [f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk]
12981298
# fields is empty or consists of the invalid "id" field
12991299
if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
13001300
return [

django/db/models/fields/related_descriptors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def get_prefetch_queryset(self, instances, queryset=None):
122122
# The check for len(...) == 1 is a special case that allows the query
123123
# to be join-less and smaller. Refs #21760.
124124
if self.field.remote_field.is_hidden() or len(self.field.foreign_related_fields) == 1:
125-
query = {'%s__in' % related_field.name: set(instance_attr(inst)[0] for inst in instances)}
125+
query = {'%s__in' % related_field.name: {instance_attr(inst)[0] for inst in instances}}
126126
else:
127127
query = {'%s__in' % self.field.related_query_name(): instances}
128128
queryset = queryset.filter(**query)

django/db/models/options.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
PROXY_PARENTS = object()
2222

23-
EMPTY_RELATION_TREE = tuple()
23+
EMPTY_RELATION_TREE = ()
2424

2525
IMMUTABLE_WARNING = (
2626
"The return type of '%s' should never be mutated. If you want to manipulate this list "

django/db/models/sql/query.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -1251,8 +1251,7 @@ def add_q(self, q_object):
12511251
# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
12521252
# rel_a doesn't produce any rows, then the whole condition must fail.
12531253
# So, demotion is OK.
1254-
existing_inner = set(
1255-
(a for a in self.alias_map if self.alias_map[a].join_type == INNER))
1254+
existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}
12561255
clause, _ = self._add_q(q_object, self.used_aliases)
12571256
if clause:
12581257
self.where.add(clause, AND)
@@ -1437,8 +1436,8 @@ def trim_joins(self, targets, joins, path):
14371436
for pos, info in enumerate(reversed(path)):
14381437
if len(joins) == 1 or not info.direct:
14391438
break
1440-
join_targets = set(t.column for t in info.join_field.foreign_related_fields)
1441-
cur_targets = set(t.column for t in targets)
1439+
join_targets = {t.column for t in info.join_field.foreign_related_fields}
1440+
cur_targets = {t.column for t in targets}
14421441
if not cur_targets.issubset(join_targets):
14431442
break
14441443
targets_dict = {r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets}

django/forms/boundfield.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,10 @@ def subwidgets(self):
4747
id_ = self.field.widget.attrs.get('id') or self.auto_id
4848
attrs = {'id': id_} if id_ else {}
4949
attrs = self.build_widget_attrs(attrs)
50-
return list(
50+
return [
5151
BoundWidget(self.field.widget, widget, self.form.renderer)
5252
for widget in self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs)
53-
)
53+
]
5454

5555
def __bool__(self):
5656
# BoundField evaluates to True even if it doesn't have subwidgets.

django/forms/fields.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -873,8 +873,8 @@ def has_changed(self, initial, data):
873873
data = []
874874
if len(initial) != len(data):
875875
return True
876-
initial_set = set(str(value) for value in initial)
877-
data_set = set(str(value) for value in data)
876+
initial_set = {str(value) for value in initial}
877+
data_set = {str(value) for value in data}
878878
return data_set != initial_set
879879

880880

django/forms/models.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1289,7 +1289,7 @@ def _check_values(self, value):
12891289
params={'pk': pk},
12901290
)
12911291
qs = self.queryset.filter(**{'%s__in' % key: value})
1292-
pks = set(str(getattr(o, key)) for o in qs)
1292+
pks = {str(getattr(o, key)) for o in qs}
12931293
for val in value:
12941294
if str(val) not in pks:
12951295
raise ValidationError(
@@ -1313,8 +1313,8 @@ def has_changed(self, initial, data):
13131313
data = []
13141314
if len(initial) != len(data):
13151315
return True
1316-
initial_set = set(str(value) for value in self.prepare_value(initial))
1317-
data_set = set(str(value) for value in data)
1316+
initial_set = {str(value) for value in self.prepare_value(initial)}
1317+
data_set = {str(value) for value in data}
13181318
return data_set != initial_set
13191319

13201320

django/utils/cache.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ def patch_vary_headers(response, newheaders):
287287
else:
288288
vary_headers = []
289289
# Use .lower() here so we treat headers as case-insensitive.
290-
existing_headers = set(header.lower() for header in vary_headers)
290+
existing_headers = {header.lower() for header in vary_headers}
291291
additional_headers = [newheader for newheader in newheaders
292292
if newheader.lower() not in existing_headers]
293293
response['Vary'] = ', '.join(vary_headers + additional_headers)
@@ -300,7 +300,7 @@ def has_vary_header(response, header_query):
300300
if not response.has_header('Vary'):
301301
return False
302302
vary_headers = cc_delim_re.split(response['Vary'])
303-
existing_headers = set(header.lower() for header in vary_headers)
303+
existing_headers = {header.lower() for header in vary_headers}
304304
return header_query.lower() in existing_headers
305305

306306

django/views/i18n.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def get(self, request, *args, **kwargs):
230230
return self.render_to_response(context)
231231

232232
def get_paths(self, packages):
233-
allowable_packages = dict((app_config.name, app_config) for app_config in apps.get_app_configs())
233+
allowable_packages = {app_config.name: app_config for app_config in apps.get_app_configs()}
234234
app_configs = [allowable_packages[p] for p in packages if p in allowable_packages]
235235
# paths of requested packages
236236
return [os.path.join(app.path, 'locale') for app in app_configs]

docs/_ext/djangodocs.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,7 @@ def visit_desc_parameterlist(self, node):
250250
self.first_param = 1
251251
self.optional_param_level = 0
252252
self.param_separator = node.child_text_separator
253-
self.required_params_left = sum([isinstance(c, addnodes.desc_parameter)
254-
for c in node.children])
253+
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children)
255254

256255
def depart_desc_parameterlist(self, node):
257256
self.body.append(')')

scripts/manage_translations.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def lang_stats(resources=None, languages=None):
114114

115115
for name, dir_ in locale_dirs:
116116
print("\nShowing translations stats for '%s':" % name)
117-
langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_')])
117+
langs = sorted(d for d in os.listdir(dir_) if not d.startswith('_'))
118118
for lang in langs:
119119
if languages and lang not in languages:
120120
continue
@@ -142,7 +142,7 @@ def fetch(resources=None, languages=None):
142142
# Transifex pull
143143
if languages is None:
144144
call('tx pull -r %(res)s -a -f --minimum-perc=5' % {'res': _tx_resource_for_name(name)}, shell=True)
145-
target_langs = sorted([d for d in os.listdir(dir_) if not d.startswith('_') and d != 'en'])
145+
target_langs = sorted(d for d in os.listdir(dir_) if not d.startswith('_') and d != 'en')
146146
else:
147147
for lang in languages:
148148
call('tx pull -r %(res)s -f -l %(lang)s' % {

tests/admin_views/urls.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
url(r'^test_admin/admin/secure-view2/$', views.secure_view2, name='secure_view2'),
99
url(r'^test_admin/admin/', admin.site.urls),
1010
url(r'^test_admin/admin2/', customadmin.site.urls),
11-
url(r'^test_admin/admin3/', (admin.site.get_urls(), 'admin', 'admin3'), dict(form_url='pony')),
11+
url(r'^test_admin/admin3/', (admin.site.get_urls(), 'admin', 'admin3'), {'form_url': 'pony'}),
1212
url(r'^test_admin/admin4/', customadmin.simple_site.urls),
1313
url(r'^test_admin/admin5/', admin.site2.urls),
1414
url(r'^test_admin/admin7/', admin.site7.urls),

tests/admin_widgets/tests.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -564,14 +564,14 @@ def test_render(self):
564564
w.render('test', [m1.pk, m2.pk], attrs={}), (
565565
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" />'
566566
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
567-
) % dict(m1pk=m1.pk, m2pk=m2.pk)
567+
) % {'m1pk': m1.pk, 'm2pk': m2.pk}
568568
)
569569

570570
self.assertHTMLEqual(
571571
w.render('test', [m1.pk]), (
572572
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
573573
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
574-
) % dict(m1pk=m1.pk)
574+
) % {'m1pk': m1.pk}
575575
)
576576

577577
def test_m2m_related_model_not_in_admin(self):

tests/aggregation/tests.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1114,7 +1114,7 @@ class MySum(Sum):
11141114
# test completely changing how the output is rendered
11151115
def lower_case_function_override(self, compiler, connection):
11161116
sql, params = compiler.compile(self.source_expressions[0])
1117-
substitutions = dict(function=self.function.lower(), expressions=sql)
1117+
substitutions = {'function': self.function.lower(), 'expressions': sql}
11181118
substitutions.update(self.extra)
11191119
return self.template % substitutions, params
11201120
setattr(MySum, 'as_' + connection.vendor, lower_case_function_override)
@@ -1141,7 +1141,7 @@ def lower_case_function_super(self, compiler, connection):
11411141

11421142
# test overriding all parts of the template
11431143
def be_evil(self, compiler, connection):
1144-
substitutions = dict(function='MAX', expressions='2')
1144+
substitutions = {'function': 'MAX', 'expressions': '2'}
11451145
substitutions.update(self.extra)
11461146
return self.template % substitutions, ()
11471147
setattr(MySum, 'as_' + connection.vendor, be_evil)

tests/annotations/tests.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def test_distinct_on_with_annotation(self):
197197
name_lower=Lower('last_name'),
198198
).distinct('name_lower')
199199

200-
self.assertEqual(set(p.last_name for p in people), {'Stark', 'Roosevelt'})
200+
self.assertEqual({p.last_name for p in people}, {'Stark', 'Roosevelt'})
201201
self.assertEqual(len(people), 2)
202202

203203
people2 = Employee.objects.annotate(

0 commit comments

Comments
 (0)